示例:按值对映射进行排序
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: Canberra Key: Nepal Value: Kathmandu Key: England Value: London Key: India Value: New Delhi Key: United States Value: Washington
在上面的程序中,我们有一个名为 capitals 的变量,其中存储了国家及其各自首都的 HashMap
。
为了对映射进行排序,我们使用在一行中执行的一系列操作。
val result = capitals.toList().sortedBy { (_, value) -> value}.toMap()
- 首先,使用
toList()
将 capitals 转换为列表。 - 然后,使用
sortedBy()
按值{ (_, value) -> value}
对列表进行排序。我们使用_
表示键,因为我们不使用它进行排序。 - 最后,我们使用
toMap()
将其转换回映射,并存储在 result 中。
这是等效的 Java 代码:按值对映射进行排序的 Java 程序。