The syntax of Map.maxOfWithOrNull() extension function is:
fun <K, V, R> Map<out K, V>.maxOfWithOrNull( comparator: Comparator<in R>, selector: (Entry<K, V>) -> R ): R?
This maxOfWithOrNull() extension function of Map returns the largest value according to the provided comparator among all values produced by selector function applied to each entry in the map or null if there are no entries.
In this example,
map1
with key-value pairs.maxOfWithOrNull()
function on map1
with a reverse comparator and a selector that returns values.map1
.fun main(args: Array<String>) {
val map1 = mapOf("key1" to 1, "key2" to 2, "key3" to 3)
val result = map1.maxOfWithOrNull(Comparator.reverseOrder(), { it.value })
println(result)
}
1
In this example,
map2
with key-value pairs.maxOfWithOrNull()
function on map2
with a reverse comparator and a selector that returns key lengths.map2
.fun main(args: Array<String>) {
val map2 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val result = map2.maxOfWithOrNull(Comparator.reverseOrder(), { it.key.length })
println(result)
}
5
In this Kotlin tutorial, we learned about maxOfWithOrNull() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.