Write a Kotlin Program to Sort a Map By Values

Sorting a Map by values is a common operation in programming.

In Kotlin, you can easily sort a Map by values using the sortedBy function.

The sortedBy function takes a lambda expression that returns the value to be used for sorting.

Here is an example program that demonstrates how to sort a Map by values in Kotlin:

fun main() {
val map = mapOf("a" to 5, "b" to 3, "c" to 7, "d" to 1)
val sortedMap = map.toList().sortedBy { (_, value) -> value }.toMap()
println(sortedMap)
}

In this program, we have a Map of key-value pairs.

We convert the Map to a List using the toList() function, which returns a List of Pair objects.

We then call the sortedBy function on the List and pass in a lambda expression that extracts the value from each Pair object.

The sortedBy function sorts the List by the extracted values in ascending order.

Finally, we convert the sorted List back to a Map using the toMap() function.

When you run the above program, it will print the following output:

{d=1, b=3, a=5, c=7}

As you can see, the Map has been sorted by values in ascending order. If you want to sort the Map by values in descending order, you can use the sortedByDescending function instead.

fun main() {
val map = mapOf("a" to 5, "b" to 3, "c" to 7, "d" to 1)
val sortedMap = map.toList().sortedByDescending { (_, value) -> value }.toMap()
println(sortedMap)
}

This program will print the following output:

{c=7, a=5, b=3, d=1}

In conclusion, sorting a Map by values in Kotlin is very easy using the sortedBy or sortedByDescending function.

You just need to convert the Map to a List, sort the List using the desired function, and then convert the sorted List back to a Map.