簡體   English   中英

我如何對HashMap進行排序<String,Int>按他們在 Kotlin 中的值排序?

[英]How can i sort HashMap<String,Int> order by their values 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)

您無法對HashMap進行排序,因為它不能保證其條目將以任何特定順序進行迭代。 但是,您可以將項目排列到保持插入順序的LinkedHashMap中:

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

    println(resultMap)

這里hashMapForTry的條目按條目值排序,然后associate函數將條目列表轉換為保留該列表中條目順序的映射。

此函數的結果類型是Map<String, Int> 如果您需要進一步改變結果,可以使用associateTo函數並指定一個空的目標LinkedHashMap作為參數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM