使用Groovy按降序排序Map值

8

我是一名有用的助手,可以为您翻译文本。

我有一个 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.

我在这里哪里出了问题?


你的意思是对值进行排序吗?而不是像问题中那样对键进行排序? - tim_yates
2个回答

15

只需要执行:

​def m = [a:​5, b:12, c:3, d:9]
def sorted = m.sort { a, b -> b.value <=> a.value }

14
另一个选项是:m.sort { -it.value }。建议使用该选项,它可以按值的降序对字典进行排序。请注意,此代码片段为Kotlin语言。 - Steinar
1
@tim_yates 你好,能否解释一下这个闭包的含义 a, b -> b.value <=> a.value .. 谢谢 :) - user3714598
1
@user3714598,“<=>”是“太空船操作符”。它委托给compareTo方法。请参见此处的文档。 - AutonomousApps

1
要进行排序,Tim的实现是最好的选择。但如果你只是想知道为什么你的示例代码不能按照你的期望工作,答案是变量“sorted”需要是LinkedHashMap类型,而不仅仅是HashMap。你可以明确地设置它:
Map<String,Integer> sorted = new LinkedHashMap<String,Integer>()

或者,只需这样做:

Map<String,Integer> sorted = [:]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接