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
originalMap.toList()
converts themHashMap
to a list of pairs..drop(1)
removes the first element from the list..sortedBy { it.second }
sorts the remaining list by the values (second element of each pair)..toMap()
converts the sorted list back to aHashMap
.linkedMapOf(originalMap.toList().first())
creates a newLinkedHashMap
one with the first element.- The
+
operator combines the first element and the sorted map. - The final
resultMap
is printed.
Comments
Post a Comment