【问题标题】:Sorting Map values in descending order with Groovy使用 Groovy 对 Map 值进行降序排序
【发布时间】:2014-10-29 20:31:36
【问题描述】:

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

我哪里错了?

【问题讨论】:

  • 您的意思是对值进行排序?不是问题中的键?

标签: sorting groovy map


【解决方案1】:

只要做:

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

【讨论】:

  • 另一种选择就是:m.sort { -it.value }
  • @tim_yates 嗨,你能解释一下这个闭包是什么意思 a, b -> b.value a.value .. 谢谢 :)
  • @user3714598, &lt;=&gt; 是“宇宙飞船操作员”。它委托给compareTo 方法。有关文档,请参阅 here
【解决方案2】:

要进行排序,Tim 的实现是要走的路。但是,如果您只是想知道为什么您的示例代码不能按预期工作,答案是变量 'sorted' 需要是 LinkedHashMap 类型,而不仅仅是 HashMap。您可以明确设置:

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

或者,只需这样做:

Map<String,Integer> sorted = [:]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-09
    • 2021-10-12
    • 2018-09-05
    • 2012-07-23
    • 2016-03-10
    • 2023-04-07
    相关资源
    最近更新 更多