Java:使用CollatorKey对集合进行排序 [英] Java: Sort a Collection using a CollatorKey
问题描述
我想要实现的是通过字符串值对对象的集合进行排序。但是,使用collator以依赖于语言环境的方式。由于性能原因,我不想使用Collator compare()方法(如下面的代码中)而不是CollationKey类,因为java API声明使用CollationKey要快得多。
但是如何使用CollationKey实现compareTo()方法?据我所知,如果我要使用CollationKey,我必须自己完全编写所有的比较方法。所以我甚至不再能够使用Collections.sort()方法......我非常感谢一个易于理解的示例,以及使用CollationKey对Person对象集合进行排序的最有效实现。 / p>
谢谢!
public class Person实现Comparable< Person> {
String lastname;
public int compareTo(Person person){
//这可行,但它不是表现良好的最佳实现
Collator instance = Collator.getInstance(Locale.ITALY) ;
return instance.compare(lastname,person.lastname);
}
}
...
ArrayList list = new ArrayList();
人员1 =新人(foo);
list.add(person1);
人员2 =新人(酒吧);
list.add(person2);
Collections.sort(list);
...
class Person实现Comparable< Person> {
private static final Collator collator = Collator.getInstance(Locale.ITALY);
private final String lastname;
私人最终CollationKey键;
Person(String lastname){
this.lastname = lastname;
this.key = collator.getCollationKey(lastname);
}
public int compareTo(Person person){
return key.compareTo(person.key);
}
}
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);
...
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);
}
}
这篇关于Java:使用CollatorKey对集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!