Java:使用Collat​​orKey对集合进行排序

我想要实现的是通过字符串值对对象的集合进行排序。 但是,使用collat​​or以依赖于语言环境的方式。 由于性能原因,我不想使用Collat​​or compare()方法(如下面的代码中)而不是Collat​​ionKey类,因为java API声明使用Collat​​ionKey要快得多。

但是如何使用Collat​​ionKey实现compareTo()方法? 据我所知,如果我要使用Collat​​ionKey,我必须自己完全编写所有的比较方法。 所以我甚至不能再使用Collections.sort()方法……我非常感谢一个易于理解的示例,以及使用Collat​​ionKey对Person对象进行排序的最有效实现。

谢谢!

public class Person implements Comparable { String lastname; public int compareTo(Person person) { //This works but it is not the best implementation for a good performance Collator instance = Collator.getInstance(Locale.ITALY); return instance.compare(lastname, person.lastname); } } ... ArrayList list = new ArrayList(); Person person1 = new Person("foo"); list.add(person1); Person person2 = new Person("bar"); list.add(person2); Collections.sort(list); ... 

 class Person implements Comparable { 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); } } 
  1. 创建一个SortedMap m,其中T是要使用CollationKeys的对象的类型。 您可以使用TreeMap作为实现
  2. 对于要排序的每个e元素, m.put(collator.getCollationKey(e.{getStringYouWantToSortOn}), e);

迭代m.values()应该产生你的对象,使用CollationKeys按你想要的字符串CollationKeys

我认为这不是有效的,但应该有效。

使用比较器而不是使Person Comparable。 您的Comparator可以使用2个Persion实例并根据某些Collat​​or实例进行比较。 然后打电话

 Collections.sort(list, myPersonComparator);