Groovy   发布时间:2022-04-12  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用Groovy按降序对Map值进行排序大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有@L_979_1@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 }

大佬总结

以上是大佬教程为你收集整理的使用Groovy按降序对Map值进行排序全部内容,希望文章能够帮你解决使用Groovy按降序对Map值进行排序所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。