在此程序中,您將學(xué)習(xí)按Kotlin中的值對(duì)給定的map進(jìn)行排序。
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)
}
}運(yùn)行該程序時(shí),輸出為:
Key: Australia Value: Canberra Key: Nepal Value: Kathmandu Key: England Value: London Key: India Value: New Delhi Key: United States Value: Washington
在上面的程序中,我們有一個(gè) HashMap,將各國及其各自的首都存儲(chǔ)在一個(gè)可變的 capitals 中。
為了對(duì)map進(jìn)行排序,我們使用在一行中執(zhí)行的一系列操作:
val result = capitals.toList().sortedBy { (_, value) -> value}.toMap()首先,使用toList()將capitals轉(zhuǎn)換為列表。
然后,sortedBy()用于按值{(_,value)-> value}對(duì)列表進(jìn)行排序。 我們使用 _ 作為鍵,因?yàn)槲覀儾皇褂盟M(jìn)行排序。
最后,我們使用toMap()將其轉(zhuǎn)換回map,并將其存儲(chǔ)在result中。
以下是等效的Java代碼:按值對(duì)map進(jìn)行排序的Java程序。