Java:使用 CollatorKey 对集合进行排序
我想要实现的是按字符串值对对象集合进行排序。但是,以依赖于语言环境的方式使用整理器。由于性能原因,我不想使用 Collatorcompare() 方法(如下代码所示),而是使用 CollationKey 类,因为 java API 声明使用 CollationKey 要快得多。
但是如何使用 CollationKey 实现compareTo() 方法呢?据我了解,如果我要使用 CollationKey,我必须自己完全编写所有比较方法。因此,我什至将不再能够使用 Collections.sort() 方法...我非常感谢一个易于理解的示例,以及使用 CollationKey 对 Person 对象集合进行排序的最有效的实现。
谢谢你!
public class Person implements Comparable<Person> {
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);
...
what I would like to achieve is to sort a colletion of objects by a string value. However in a locale dependant way using a collator. Due to performance reasons I do not want to use the Collator compare() method (as below in the code) rather the CollationKey class, as the java API states the using a CollationKey is much faster.
But how do I implement the compareTo() method using the CollationKey? As far as I understood it, I have to completely write all the comparison Methods on my own if I will be using a CollationKey. So I will even no longer be able to use the Collections.sort() methods... I am very thankfull for an example that is easy to understand and a the most efficient implementation to sort the Collection of Person objects using a CollationKey.
Thank you!
public class Person implements Comparable<Person> {
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);
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
CollationKeys
排序的对象的类型。您可以使用 TreeMap 作为实现迭代
m.values()
应该生成您的对象,并使用CollationKeys
按您想要的字符串排序。我相信这效率不高,但应该有效。
CollationKeys
. You can useTreeMap
as the implementationm.put(collator.getCollationKey(e.{getStringYouWantToSortOn}), e);
Iterating over
m.values()
should yield your objects, sorted by the string you want usingCollationKeys
.I believe this is not efficient, but it should work.
使用比较器而不是使人具有可比性。您的 Comparator 可以采用 2 个 Persion 实例,并根据某个 Collator 实例对它们进行比较。然后打电话
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