[英]Sorting Map values in descending order with Groovy
我有一個Map<String,Integer>
其條目(鍵)需要按降序排序。 例如,如果地圖如下所示:
"a" => 5
"b" => 3
"c" => 12
"d" => 9
排序后需要看起來像:
"c" => 12
"d" => 9
"a" => 5
"b" => 3
迄今為止我最好的嘗試:
def test() {
Map<String,Integer> toSort = new HashMap<String,Integer>()
toSort.put("a", 5)
toSort.put("b", 3)
toSort.put("c", 12)
toSort.put("d", 9)
Map<String,Integer> sorted = sortMapDesc(toSort)
sorted.each {
println "${it.key} has a value of ${it.value}."
}
}
def sortMapDesc(Map<String,Integer> toSort) {
println "Sorting..."
println toSort
// The map of properly sorted entries.
Map<String,Integer> sorted = new HashMap<String,Integer>()
// Keep scanning the map for the key with the highest value. When we find
// it, add it as the next entry to the 'sorted' map, and then zero it out
// so it won't show up as the highest on subsequent scans/passes. Stop scanning
// when the entire 'toSort' map contains keys with zeros.
while(!mapIsAllZeros(toSort)) {
int highest = -1
String highestKey = ""
toSort.each {
if(it.value > highest) {
highest = it.value
highestKey = it.key
}
}
toSort.put(highestKey, 0)
sorted.put(highestKey, highest)
}
sorted
}
def mapIsAllZeros(Map<String,Integer> toCheck) {
toCheck.values().every{!it}
}
當我運行test()
我得到以下輸出:
Sorting...
[d:9, b:3, c:12, a:5]
d has a value of 9.
b has a value of 3.
c has a value of 12.
a has a value of 5.
我在哪里錯了?
做就是了:
def m = [a:5, b:12, c:3, d:9]
def sorted = m.sort { a, b -> b.value <=> a.value }
為了進行排序,Tim的實施是要走的路。 但是,如果您只是想知道為什么您的示例代碼不能按預期工作,那么答案是變量'sorted'需要是LinkedHashMap類型,而不僅僅是HashMap。 您可以明確設置它:
Map<String,Integer> sorted = new LinkedHashMap<String,Integer>()
或者,只需這樣做:
Map<String,Integer> sorted = [:]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.