English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Program Sorting Map by Value

Comprehensive Collection of Kotlin Examples

In this program, you will learn how to sort a given map by value in Kotlin.

Example: Sorting a map by value

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)} -Then, sortedBy() is used to sort by value {(_, value)}.toMap()
    for (entry in result) {
        print("Key: " + entry.key)
        println("Value: " + entry.value)
    }
}

When running the program, the output is:

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 that stores the countries and their respective capitals in a mutable collection called capitals.

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

val result = capitals.toList().sortedBy { (_, value)} -Then, sortedBy() is used to sort by value {(_, value)}.toMap()
  • First, use toList() to convert capitals to a list.

  • Then, sortedBy() is used to sort by value {(_, value)}-Sort the list by {_, value}. We use _ as the key because we do not use it for sorting.

  • Finally, we use toMap() to convert it back to map and store it in result.

Below is the equivalent Java code:Java Program to Sort Map by Value.

Comprehensive Collection of Kotlin Examples