문제

내가 달성하고자하는 것은 문자열 값으로 객체의 공동을 정렬하는 것입니다. 그러나 Collator를 사용하는 로케일의 종속 방식으로. 성능의 이유로 인해 Java API가 CollationKey를 사용하는 것이 훨씬 빠르기 때문에 Collator Compare () 메소드 (코드에서와 같이)를 Collationkey 클래스를 사용하고 싶지 않습니다.

그러나 CollationKey를 사용하여 비교 () 메소드를 어떻게 구현합니까? 내가 이해 한 한, 나는 collationkey를 사용하려면 모든 비교 방법을 직접 작성해야합니다. 따라서 Collections.sort () 메소드를 더 이상 사용할 수 없습니다. 이해하기 쉬운 예와 Collationkey를 사용하여 사람 객체의 모음을 정렬하는 가장 효율적인 구현에 대해 매우 감사합니다.

고맙습니다!

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

}

다른 팁

  1. 정렬 맵 m을 만듭니다. 여기서 t는 정렬 할 객체의 유형입니다. CollationKeys. 당신이 사용할 수있는 TreeMap 구현으로
  2. 정렬하려는 각 E 요소에 대해 m.put(collator.getCollationKey(e.{getStringYouWantToSortOn}), e);

반복 m.values() 사용하려는 문자열로 정렬 된 객체를 생성해야합니다. CollationKeys.

나는 이것이 효율적이지 않다고 생각하지만 효과가 있어야합니다.

사람을 비슷하게 만드는 대신 비교기를 사용하십시오. 비교기는 2 개의 인스턴스 인스턴스를 가져 와서 일부 콜레이터 인스턴스를 기반으로 비교할 수 있습니다. 그런 다음 전화하십시오

Collections.sort(list, myPersonComparator);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top