Home > OS >  Sort a Map<Int, Int> by value then by key
Sort a Map<Int, Int> by value then by key

Time:10-01

I've got a map of values where the key is a digit and the value is the number of the occurrences of the digit in a string

example :

6644241333431
{6:2,4:4,2:1,3:4,1:2}

I would like to get the digit with the most occurrences, if two numbers are equals then get the smaller one. I feel like it could be done with ".sortedBy{ (key, value) -> ... }" or even "compareBy{ it.first }.thenBy{it.second}".

CodePudding user response:

You can do this almost the way you described:

map.entries
    .sortedWith(compareByDescending<Map.Entry<Int, Int>> { it.value }.thenByDescending { it.key })

It returns a list, not a map. You can convert it back to map if you need.

If you only need a single, maximum value, then sorting is really not necessary and you can find it in a similar way as above:

map.maxOfWith(compareBy<Map.Entry<Int, Int>> { it.value }.thenBy { it.key }) { it }
  • Related