简体   繁体   English

我如何对HashMap进行排序<String,Int>按他们在 Kotlin 中的值排序?

[英]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.

相关问题 如何将字符串的某些字符与HashMap的值交换 <String,String> 在科特林? - How do I swap some characters of a String with values of a HashMap<String,String> in Kotlin? 如何对字符串和int值的数组进行排序,使用字母和“反向” - 字母顺序对多个属性进行排序 - How to sort array of string and int values, multiple attributes with alphabetical and “reversed”-alphabetical order 如何订购字典列表 <int, string> 基于Dictionary int值? - How can I order a List of Dictionary<int, string> based on Dictionary int value? 如何排序清单 <int> 使用另一个列表 <int> ? - How can I Sort a List<int> using another List<int>? 如何在列表中存储HashMap <String,ArrayList <String >>? - How can I store HashMap<String, ArrayList<String>> inside a list? 如何将int sort切换为String sort? - How to switch int sort to String sort? Kotlin:改变类型MutableList <java.util.hashmap<int, int> > 至 kotlin.collections.HashMap <int, int></int,></java.util.hashmap<int,> - Kotlin: change the type MutableList<java.util.HashMap<Int, Int>> to kotlin.collections.HashMap<Int, Int> 如何按自定义顺序对值进行排序 - How to sort values in customized order 我该如何排序列表 <Tuple<int, double> &gt; - How can i Sort a List<Tuple<int, double>> 如何将RDD [Array [String]]转换为RDD [(Int,HashMap [String,List])]? - How to convert RDD[Array[String]] to RDD[(Int, HashMap[String, List])]?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM