Kotlin Program to Sort a Map By Values

In this program, you'll learn to sort a given map by values in Kotlin.

Example: 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)
    }
}

When you run the program, the output will be:

Key: Australia Value: Canberra
Key: Nepal Value: Kathmandu
Key: England Value: London
Key: India Value: New Delhi
Key: United States Value: Washington

In the above program, we have a HashMap with countries and their respective capitals stored in a variable capitals.

To sort the map, we use a series of operations executed in a single line:

val result = capitals.toList().sortedBy { (_, value) -> value}.toMap()
  • First, capitals is converted to a list using toList().
  • Then, sortedBy() is used to sort the list by value { (_, value) -> value}. We use _ for key because we don't use it for sorting.
  • Finally, we convert it back to map using toMap() and store it in result.

Here's the equivalent Java code: Java program to sort a map by values.