Skip to main content

How to sort a HashMap by keys or values in Kotlin

How to sort a HashMap by keys or values in Kotlin.

Sorting a HashMap by Keys in Kotlin

To sort a HashMap by its keys in Kotlin, you can follow the steps below:

  1. Create a HashMap with key-value pairs.
  2. Convert the HashMap to a List of Map.Entry objects using the toList() method.
  3. Sort the list of entries by keys using the sortedBy() method.
  4. Convert the sorted list of entries back to a LinkedHashMap to maintain the order of the sorted keys.

Here's an example code snippet that demonstrates how to sort a HashMap by keys in Kotlin:

fun main() {
val hashMap = hashMapOf(
4 to "Apple",
2 to "Banana",
1 to "Orange",
3 to "Grapes"
)

val sortedMap = hashMap.toList()
.sortedBy { (key, _) -> key }
.toMap()
.toSortedMap()

println(sortedMap)
}

In this example, we have a HashMap hashMap with integer keys and string values. We convert this HashMap to a list of entries using toList(), then sort the list using sortedBy() by extracting the keys from each entry. Finally, we convert the sorted list back to a LinkedHashMap using toMap() and toSortedMap() to preserve the order of the sorted keys.

When you run the above code, it will output the sorted HashMap:

{1=Orange, 2=Banana, 3=Grapes, 4=Apple}

Sorting a HashMap by Values in Kotlin

To sort a HashMap by its values in Kotlin, you can follow the steps below:

  1. Create a HashMap with key-value pairs.
  2. Convert the HashMap to a List of Map.Entry objects using the toList() method.
  3. Sort the list of entries by values using the sortedBy() method.
  4. Convert the sorted list of entries back to a LinkedHashMap to maintain the order of the sorted values.

Here's an example code snippet that demonstrates how to sort a HashMap by values in Kotlin:

fun main() {
val hashMap = hashMapOf(
4 to "Apple",
2 to "Banana",
1 to "Orange",
3 to "Grapes"
)

val sortedMap = hashMap.toList()
.sortedBy { (_, value) -> value }
.toMap()
.toSortedMap()

println(sortedMap)
}

In this example, we have a HashMap hashMap with integer keys and string values. We convert this HashMap to a list of entries using toList(), then sort the list using sortedBy() by extracting the values from each entry. Finally, we convert the sorted list back to a LinkedHashMap using toMap() and toSortedMap() to preserve the order of the sorted values.

When you run the above code, it will output the sorted HashMap:

{4=Apple, 2=Banana, 3=Grapes, 1=Orange}

That's it! You now know how to sort a HashMap by keys or values in Kotlin.