Java: Sort a Collection using a CollatorKey

2019-03-28 03:49发布

问题:

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);
...

回答1:

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);
  }

}


回答2:

  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.



回答3:

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);