![](/img/trans.png)
[英]How to sort an list first letter ascending and last letter decending in java?
[英]Java - How to sort a map values according to their first letter?
我有一個Java映射,使用此代碼按字母順序對其字符串值進行排序:
public <K, V> LinkedHashMap<K, V> sortMapByValues( Map<K, V> map ) {
SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(
new Comparator<Map.Entry<K, V>>() {
@Override
public int compare( Map.Entry<K, V> e1, Map.Entry<K, V> e2 ) {
// Sort this word alphabetically in the map :
String a = (String)e1.getValue();
String b = (String)e2.getValue();
int diff = a.compareToIgnoreCase( b );
if (diff == 0)
diff = a.compareTo(b);
return diff != 0 ? diff : 1; // Fix words having the same spelling.
}
}
);
sortedEntries.addAll( map.entrySet() );
LinkedHashMap<K, V> sortedMap = new LinkedHashMap<K, V>();
for( Map.Entry<K, V> sortedEntry: sortedEntries )
sortedMap.put( sortedEntry.getKey(), sortedEntry.getValue() );
return sortedMap;
}
由於Map具有成千上萬個值,因此上述代碼可以足夠快地運行,從而給出我想要的快速結果。 現在,我需要更改此代碼並更新它,以便根據另一種條件而不是按字母順序對Map值進行排序。
我有一個字母的變體ArrayList,例如:
ArrayList lettersArrayList = new ArrayList<String>( Arrays.asList( "E", "C", "A", "Z", "Q", "R", "B", "L", "D", ... ) );
該ArrayList中的字母值由用戶指定,因此它們可能具有任何其他字母值和順序。 我需要根據此ArrayList對Map的String值進行排序,因此,以“ E”開頭的單詞首先出現,然后出現以“ C”開頭的單詞,依此類推。 這可能嗎?
首先,您的比較器不正確:
return diff != 0 ? diff : 1;
如果a
和b
具有相同的拼寫,比較a
到b
給出1,這意味着a > b
,以及比較b
到a
還給出了1,這意味着b > a
。 你可以用
return diff != 0 ? diff : Integer.compare(System.identityHashCode(e1), System.identityHashCode(e2));
是(幾乎)正確的。 如果您使用大量內存,並且兩個單獨的對象碰巧以相同的系統哈希碼結尾,那么當兩個條目實際上不同時,這仍然可以使它們相等。
現在,要回答您的問題,您所需要做的就是比較兩個條目的第一個字母的索引:
String a = (String)e1.getValue();
String b = (String)e2.getValue();
int index1 = list.indexOf(a.substring(0, 1));
int index2 = list.indexOf(b.substring(0, 1));
int diff = Integer.compare(index1, index2);
這會起作用,但效率極低,因為
因此,應該使用HashMap<Character, Integer>
而不是List<String>
來存儲字母,其中每個字母都將與其位置相關聯。 此映射中的查找為O(1),使比較器快得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.