To sort a map by values in Kotlin, you can convert the map entries to a list, sort the list by values, and then convert it back to a map. This method allows you to sort the map based on values.
We can sort a map by values in Kotlin by converting the map entries to a list, sorting the list by values, and then converting it back to a map.
For example,
unsortedMap
with some key-value pairs. In this example, the map has string keys and integer values.sortedBy
function.toMap
function.println
function to verify the sorting.fun main() {
// Declare and initialize an unsorted map
val unsortedMap = mapOf("apple" to 3, "banana" to 1, "cherry" to 2)
// Convert the map entries to a list and sort the list by values
val sortedEntries = unsortedMap.entries.sortedBy { it.value }
// Create a new map from the sorted list of map entries
val sortedMap = sortedEntries.toMap()
// Print the sorted map
println("Sorted Map by Values: $sortedMap")
}
Sorted Map by Values: {banana=1, cherry=2, apple=3}
We can sort a map by values in descending order in Kotlin by converting the map entries to a list, sorting the list by values in descending order, and then converting it back to a map.
For example,
unsortedMap
with some key-value pairs. In this example, the map has string keys and integer values.sortedByDescending
function.toMap
function.println
function to verify the sorting.fun main() {
// Declare and initialize an unsorted map
val unsortedMap = mapOf("apple" to 3, "banana" to 1, "cherry" to 2)
// Convert the map entries to a list and sort the list by values in descending order
val sortedEntries = unsortedMap.entries.sortedByDescending { it.value }
// Create a new map from the sorted list of map entries
val sortedMap = sortedEntries.toMap()
// Print the sorted map
println("Sorted Map by Values (Descending): $sortedMap")
}
Sorted Map by Values (Descending): {apple=3, cherry=2, banana=1}
We can sort a map with numeric keys by values in Kotlin by converting the map entries to a list, sorting the list by values, and then converting it back to a map.
For example,
unsortedMap
with some key-value pairs. In this example, the map has integer keys and string values.sortedBy
function.toMap
function.println
function to verify the sorting.fun main() {
// Declare and initialize an unsorted map
val unsortedMap = mapOf(3 to "three", 1 to "one", 2 to "two")
// Convert the map entries to a list and sort the list by values
val sortedEntries = unsortedMap.entries.sortedBy { it.value }
// Create a new map from the sorted list of map entries
val sortedMap = sortedEntries.toMap()
// Print the sorted map
println("Sorted Map by Values: $sortedMap")
}
Sorted Map by Values: {1=one, 2=two, 3=three}
In this tutorial, we learned How to Sort a Map by Values in Kotlin language with well detailed examples.