[英]How can i sort HashMap<String,Int> order by their values in Kotlin?
Here is my example, how can i do that in Kotlin?这是我的例子,我怎么能在 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)
You cannot sort a HashMap
because it doesn't guarantee that its entries will be iterated in any particular order.您无法对HashMap
进行排序,因为它不能保证其条目将以任何特定顺序进行迭代。 You can, however, arrange the items into a LinkedHashMap
which keeps the insertion order:但是,您可以将项目排列到保持插入顺序的LinkedHashMap
中:
val resultMap = hashMapForTry.entries.sortedBy { it.value }.associate { it.toPair() }
println(resultMap)
Here the entries of hashMapForTry
are sorted by entry value, then associate
function converts the list of entries into a map that preserves the order of entries from that list.这里hashMapForTry
的条目按条目值排序,然后associate
函数将条目列表转换为保留该列表中条目顺序的映射。
The result type of this function is Map<String, Int>
.此函数的结果类型是Map<String, Int>
。 If you need to mutate the result further, you can use associateTo
function and specify an empty destination LinkedHashMap
as a parameter:如果您需要进一步改变结果,可以使用associateTo
函数并指定一个空的目标LinkedHashMap
作为参数:
....associateTo(LinkedHashMap()) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.