In this article you will learn today how to sort a given map in Kotlin.
Sort a map by values
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) } }
Result
Key: Australia Value: Canberra Key: Nepal Value: Kathmandu Key: England Value: London Key: India Value: New Delhi Key: United States Value: Washington