Search code examples
sortingkotlinhashmap

Is there a simple way to sort a HashMap by values AND keys (Kotlin)?


I know hashmaps are not sorted by default. I also know you can easily sort a HashMap's keys by using map.toSortedMap(), and their values with map.toList().sortedBy { (_, value) -> value }.

But what if you wanted to sort both? I want to sort a hashmap first by values, and then, if the values are similar, by keys. I have mainly seen examples of this being done in Java, but the code can be quite extensive. Is there a simple, intuitive way of doing what I want?

Edit: To be a little bit more precise: I want to sort the hashmap objects by their values, BUT if some values are similar, I want to sort ONLY those objects by their keys as well.


Solution

  • The easiest solution I can think of is to change the map into a list of pairs, sort it, and then make it a map again. Now take this with a grain of salt, as I honestly do not think that this might be the best way.

    It will looks something like this:

    val m = hashMapOf<String, String>()
    m.map { it.key to it.value }.sortedBy { it.first + it.second }.toMap()
    

    The sorting logic is it.first + it.second where it.first represents the key from the map, and it.second the value. You can change that logic to sort it however you like.

    Also, the .toMap() won't give you HashMap back, but a Map, you can get it back by doing something like HashMap(map), but then again, this whole process doesn't seem quite efficient to me.