[英]How to sort a HashMap in descending order (based on the value) and keep the lexigraphy order (based on key) at the same time?
[英]Sort HashMap descending by value and ascending by key at the same time
考慮以下 hashmap:
HashMap<String, Double> cityScoreMap = new HashMap<>();
具有諸如
CityB, 5.0
CityC, 10.0
CityA, 5.0
我需要按值對 hashmap 進行降序排序,但如果值相等,則按鍵升序排序:
CityC, 10.0 (highest value)
CityA, 5.0 (comes before CityB, because A < B)
CityB, 5.0 (comes after CityA)
到目前為止,嘗試按鍵分別排序,然后按值排序,但我不相信這種方法。 除了創建更多的哈希圖之外,還有什么好的方法可以做到這一點?
實現這種 Map 的最簡單方法是使用 stream。 你必須實現一個比較器。
Map<String, Double> cityScoreMap = new HashMap<>();
cityScoreMap.put("CityB", 5.0);
cityScoreMap.put("CityC", 10.0);
cityScoreMap.put("CityA", 5.0);
Comparator<Map.Entry<String, Double>> descendingValueAscendingKeyComparator = (entry1, entry2) -> {
//natural ordering of numbers is ascending, so comparing entry2 value to entry1 value makes for descending order
int cmp = entry2.getValue().compareTo(entry1.getValue());
if (cmp == 0) {
//if comparison result is zero, that means values are equal, so we are comparing keys
//we are comparing entry1 to entry2 keys for ascending order, which is natural for string
return entry1.getKey().compareTo(entry2.getKey());
}
return cmp;
};
cityScoreMap.entrySet()//get the set of entries in the map
.stream()//stream the entries
.sorted(descendingValueAscendingKeyComparator)//sort the entries with the supplied comparator
.forEach(entry -> System.out.println(entry.getKey() + ", " + entry.getValue()));//print to verify ordering
比較器定義元素的順序,這可能與它們的自然順序不同。 此比較器定義 map 中條目(鍵值對)的順序 - 首先按值降序,然后按鍵升序。 這里的條目只是打印出來的,所以你可以看到排序,但你也可以將它們存儲在另一個結構中,這樣可以保持它們的順序——例如 LinkedHashMap,無論你的實際需要是什么。
您應該從 javadoc 開始閱讀Comparator和Comparable接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.