Kotlin Program to Sort a Map By Values

Kotlin Program to Sort a Map By Values. In order to sort HashMap by values, you can first create a Comparator, which can compare two entries based on values.

Kotlin Program to Compare Strings

Source Code

fun main(args: Array<String>) {

    var capitals = hashMapOf<String, String>()
    capitals.put("pak", "islamabbad")
    capitals.put("India", "New Delhi")
    capitals.put("United States", "Washington")
    capitals.put("England", "London")
    capitals.put("Australia", "abcd ")

    val result = capitals.toList().sortedBy { (_, value) -> value}.toMap()

    for (entry in result) {
        print("Key: " + entry.key)
        println(" Value: " + entry.value)
    }
}

Output