【问题标题】:How can i sort HashMap<String,Int> order by their values in Kotlin?如何按 Kotlin 中的值对 HashMap<String,Int> 进行排序?
【发布时间】:2020-03-24 14:47:25
【问题描述】:

这是我的例子,我如何在 Kotlin 中做到这一点?

var hashMapForTry = HashMap<String,Int>()

hashMapForTry.put("Hi",5)
hashMapForTry.put("What",7)
hashMapForTry.put("How",2)
hashMapForTry.put("Go",1)
hashMapForTry.put("Ford",9)

【问题讨论】:

    标签: list sorting kotlin hashmap treemap


    【解决方案1】:

    您不能对HashMap 进行排序,因为它不能保证其条目会以任何特定顺序进行迭代。但是,您可以将项目排列到保持插入顺序的LinkedHashMap 中:

        val resultMap = hashMapForTry.entries.sortedBy { it.value }.associate { it.toPair() }
    
        println(resultMap)
    

    这里hashMapForTry 的条目按条目值排序,然后associate 函数将条目列表转换为保留该列表中条目顺序的映射。

    这个函数的结果类型是Map&lt;String, Int&gt;。如果需要进一步改变结果,可以使用associateTo 函数并指定一个空的目标LinkedHashMap 作为参数:

    ....associateTo(LinkedHashMap()) { ... }
    

    【讨论】:

    • TreeMap,它使用比较器来确定顺序
    • @AjahnCharles TreeMap 使用比较器来比较,它不能用于根据对应的对它们进行排序。
    猜你喜欢
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 2012-04-30
    相关资源
    最近更新 更多