我有我簡化,但在essense一個地圖包含了這樣一些數據的鍵值:號碼列表
Yahya, 4
John, 4
Blake, 2
Jill 2
Janoe, 6
Jilly 12
Zapon, 5
Zoe, 4
Hamed, 1
我需要訂購,這樣我得到以下輸出:
1. Jilly, 12 pts
2. Janoe, 6 pts
3. Zapon, 5 pts
4. John, 4 pts
4. Yahya, 4 pts
4. Zoe, 4 pts
7. Blake, 2 pts
7. Jill, 2 pts
9. Hamed, 1 pts
我已經使用的比較器,根據值訂購地圖值:
public <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
Comparator<K> valueComparator = new Comparator<K>() {
public int compare(K k1, K k2) {
int compare = map.get(k2).compareTo(map.get(k1));
if (compare == 0) return 1;
else return compare;
}
};
Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
和讀:How to get element position from Java Map,Order HashMap alphabetically by value和更多但不知道如何把它放在一起。
我知道你可以用它來獲取鍵值:
for (Map.Entry<String, Integer> entry : map.entrySet()){
System.out.println(entry.getKey() + " ," + entry.getValue() + " pts");
}
但是兩個功能缺失:
- 按字母順序排序,當密鑰是相同的
- 保持相同的編號,如果值是同樣的,然後跳到正確的數。
嘗試這樣:
Map<String, Integer> map = sortByValues(groupList);
int count = 1;
int counter = 1;
int previousScore = 0;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
//counter = count;
if (previousScore == entry.getValue()) {
System.out.println(counter - 1 + " " + entry.getKey() + "," + entry.getValue() + " pts");
} else {
System.out.println(counter + " " + entry.getKey() + "," + entry.getValue() + " pts");
previousScore = entry.getValue();
count++;
}
counter++;
}
任何想法表示讚賞和歡迎。任何人都可以提出一種方法來達到所需的結果嗎?
感謝您的回答,但...執行k1.compareTo(K2)是刪除重複值,而不是編號的並嘗試了各種計數之前,因此提出這個問題,因爲我不能正確的。有相同的想法,但不知道如何實施。 –
也聲明'K'爲'Comparable',與'V'相同。或者,更好的是,去掉泛型,並使用'Map',因爲這就是你真正需要的。如果你希望我們幫你弄清楚它有什麼問題,請顯示你的代碼。 –
Dima