[英]How do I swap some characters of a String with values of a HashMap<String,String> in 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.