原文: https://www.programiz.com/kotlin-programming/examples/sort-map-values
在此程序中,您将学习按 Kotlin 中的值对给定的映射进行排序。
示例:按值对映射排序
fun main(args: Array<String>) {var capitals = hashMapOf<String, String>()capitals.put("Nepal", "Kathmandu")capitals.put("India", "New Delhi")capitals.put("United States", "Washington")capitals.put("England", "London")capitals.put("Australia", "Canberra")val result = capitals.toList().sortedBy { (_, value) -> value}.toMap()for (entry in result) {print("Key: " + entry.key)println(" Value: " + entry.value)}}
运行该程序时,输出为:
Key: Australia Value: CanberraKey: Nepal Value: KathmanduKey: England Value: LondonKey: India Value: New DelhiKey: United States Value: Washington
在上述程序中,我们将HashMap和国家/地区及其各自的首都存储在变量capitals中。
为了对映射进行排序,我们使用在一行中执行的一系列操作:
val result = capitals.toList().sortedBy { (_, value) -> value}.toMap()
- 首先,使用
toList()将capitals转换为列表。 - 然后,
sortedBy()用于按值{ (_, value) -> value}对列表进行排序。 我们将_用于键,因为我们不使用它进行排序。 - 最后,我们使用
toMap()将其转换回映射,并将其存储在result中。
以下是等效的 Java 代码: Java 程序:通过值对映射进行排序。
