2009-09-14 59 views
7

我想實現的目標是按字符串值排序對象的集合。但是,在使用collat​​or的語言環境依賴方式中。由於性能原因,我不想使用Collat​​or compare()方法(如下面的代碼)而不是Collat​​ionKey類,因爲java API聲明使用Collat​​ionKey要快得多。Java:使用Collat​​orKey對一個集合進行排序

但是,如何使用Collat​​ionKey實現compareTo()方法?據我瞭解,如果我將使用Collat​​ionKey,我必須自己完全編寫所有比較方法。所以我甚至不再能夠使用Collections.sort()方法......我非常感謝一個容易理解的例子以及使用Collat​​ionKey對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); 
... 

回答

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

} 
+0

你好埃裏克森,非常感謝你的智能解決方案,我會像這樣實現它,謝謝! – jan 2009-09-16 02:03:13

0
  1. 創建一個SortedMap m,其中T是你想用CollationKeys排序的對象的類型。您可以使用TreeMap作爲實現
  2. 對於要排序的每個E元素,m.put(collator.getCollationKey(e.{getStringYouWantToSortOn}), e);

遍歷m.values()應該得到你的對象,通過你想使用CollationKeys串排序。

我認爲這不是有效的,但它應該工作。

+0

埃裏克森的回答導致更有效的解決方案。 – alex 2009-09-14 21:48:24

+0

在我的情況下,接受的解決方案無法實施,而且這個解決方案完美無缺。 – 2015-08-11 19:14:29

-2

使用比較器而不是使Person可比較。您的比較器可以採用2個Persion實例,並根據某個Collat​​or實例進行比較。然後調用

Collections.sort(list, myPersonComparator); 
+0

問題是在比較器中存儲collat​​ionKey,以便它不重複計算... – alex 2009-09-14 21:49:16

+0

啊,我看到了問題。我還沒有使用過Collat​​ors。我認爲最初的問題只是解決不斷重新獲得Collat​​or實例。 – james 2009-09-16 17:53:16

相關問題