在此程序中,您将学习按Kotlin中的值对给定的map进行排序。
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
在上面的程序中,我们有一个 HashMap,将各国及其各自的首都存储在一个可变的 capitals 中。
为了对map进行排序,我们使用在一行中执行的一系列操作:
val result = capitals.toList().sortedBy { (_, value) -> value}.toMap()首先,使用toList()将capitals转换为列表。
然后,sortedBy()用于按值{(_,value)-> value}对列表进行排序。 我们使用 _ 作为键,因为我们不使用它进行排序。
最后,我们使用toMap()将其转换回map,并将其存储在result中。
以下是等效的Java代码:按值对map进行排序的Java程序。