加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-14 16:28:19 所属栏目:大数据 来源:网络整理
导读:我有一个Map String,Integer其条目(键)需要按降序排列.例如,如果地图如下所示: "a" = 5"b" = 3"c" = 12"d" = 9 排序后需要看起来像: "c" = 12"d" = 9"a" = 5"b" = 3 迄今为止我最好的尝试: def test() { MapString,Integer toSort = new HashMapString,In
我有一个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 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读