Sort a HashMap in Kotlin in ascending order but the first element is not used in sorting

 In Kotlin, you can arrange a HashMap’s values in ascending order while preserving the first element’s original position. This can be achieved by utilizing the toList() function in conjunction with sortedBy and toMap.

Let’s take a look at an example:

fun main() {
val originalMap = hashMapOf(
"Key1" to 35,
"Key2" to 28,
"Key3" to 12,
"Key4" to 18,
// ... (add more key-value pairs as needed)
)

// Sort the HashMap by values in ascending order, excluding the first element
val sortedMap = originalMap.toList().drop(1).sortedBy { it.second }.toMap()

// Create the final sorted map with the first element
val resultMap = linkedMapOf(originalMap.toList().first()) + sortedMap

// Print the sorted map
resultMap.forEach { (key, value) ->
println("$key: $value")
}
}

Code Review

  1. originalMap.toList() converts them HashMap to a list of pairs.
  2. .drop(1) removes the first element from the list.
  3. .sortedBy { it.second } sorts the remaining list by the values (second element of each pair).
  4. .toMap() converts the sorted list back to a HashMap.
  5. linkedMapOf(originalMap.toList().first()) creates a new LinkedHashMap one with the first element.
  6. The + operator combines the first element and the sorted map.
  7. The final resultMap is printed.

Comments

Popular posts from this blog

How to Integrate or Work with Open Street Map (OSM) in an Android App (Kotlin)

ListView in android with api and volley Network Library in android Studio.

how to implement OpenStreetMap in android