I would like to find all entries with maximum value.
I've come to:
val myMap = mapOf<Int, Int>(...)
val maxEntries = myMap.maxBy { it.value }
?.let { max -> myMap.filter { it.value == max.value } }
?.entries
?: emptySet()
but I wonder if there is more idiomatic solution.
You can simplify what you have to something as follows:
val maxValue = myMap.values.maxOrNull() // or max() depending on Kotlin version
val maxEntries = myMap.filterValues { it == maxValue }
This way you keep the Map<Int, Int>
-type and I think it's more readable that way. Note that maxValue
being null
doesn't really hurt, as you will only get null
if the map is empty... filtering then on an empty map still returns an empty map. That's probably also the only* bad part of this solution. If you have an empty map, this variant constructs a new empty map when filterValues
is called.
If you mind that, then the following is more appropriate:
val maxEntries = myMap.values.maxOrNull()?.let { maxValue ->
myMap.filterValues { it == maxValue }
} ?: emptyMap()
* the only bad part besides iterating over the map twice. If you want to overcome that, then I think you have to implement your own specific function dealing with both, checking max value and collecting, at the same time.