简体   繁体   English

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

[英]Sorting Map values in descending order with Groovy

I have a Map<String,Integer> whose entries (keys) need to be sorted in order of descending value . 我有一个Map<String,Integer>其条目(键)需要按降序排序。 For instance, if the map looks like: 例如,如果地图如下所示:

"a" => 5
"b" => 3
"c" => 12
"d" => 9

The after sorting it needs to look like: 排序后需要看起来像:

"c" => 12
"d" => 9
"a" => 5
"b" => 3

My best attempt thus far: 迄今为止我最好的尝试:

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

When I run test() I get the following output: 当我运行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.

Where am I going wrong here? 我在哪里错了?

Just do: 做就是了:

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

To do the sorting, Tim's implementation is the way to go. 为了进行排序,Tim的实施是要走的路。 But if you're just wondering why your example code doesn't work as you expect, the answer is that the variable 'sorted' needs to be of type LinkedHashMap, rather than just HashMap. 但是,如果您只是想知道为什么您的示例代码不能按预期工作,那么答案是变量'sorted'需要是LinkedHashMap类型,而不仅仅是HashMap。 You can set it explicitly: 您可以明确设置它:

Map<String,Integer> sorted = new LinkedHashMap<String,Integer>()

Or, just do this: 或者,只需这样做:

Map<String,Integer> sorted = [:]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM