Java: Sort a Collection using a CollatorKey

纵饮孤独 提交于 2019-12-03 14:41:57
class Person implements Comparable<Person> {

  private static final Collator collator = Collator.getInstance(Locale.ITALY);

  private final String lastname;

  private final CollationKey key;

  Person(String lastname) {
    this.lastname = lastname;
    this.key = collator.getCollationKey(lastname);
  }

  public int compareTo(Person person) {
     return key.compareTo(person.key);
  }

}
alex
  1. Create a SortedMap m, where T is the type of the objects you want to sort using CollationKeys. You can use TreeMap as the implementation
  2. For each e element you want to sort, m.put(collator.getCollationKey(e.{getStringYouWantToSortOn}), e);

Iterating over m.values() should yield your objects, sorted by the string you want using CollationKeys.

I believe this is not efficient, but it should work.

use a Comparator instead of making Person Comparable. your Comparator can take 2 Persion instances and compare them based on some Collator instance. then call

Collections.sort(list, myPersonComparator);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!