5 "b" => 3 "c" => 12 "d" => 9 排序后它需要看起来像: "c" => 12 "-6ren">
gpt4 book ai didi

使用 Groovy 按降序对 Map 值进行排序

转载 作者:行者123 更新时间:2023-12-02 13:50:20 26 4
gpt4 key购买 nike

我有一个Map<String,Integer>其条目(键)需要按值降序顺序排序。例如,如果 map 如下所示:

"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 }

关于使用 Groovy 按降序对 Map 值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25676527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com