The syntax of Map.maxByOrNull() extension function is:
fun <K, V, R : Comparable<R>> Map<out K, V>.maxByOrNull( selector: (Entry<K, V>) -> R ): Entry<K, V>?
This maxByOrNull() extension function of Map returns the first entry yielding the largest value of the given function or null if there are no entries.
In this example,
map1
with key-value pairs.maxByOrNull()
function on map1
, applying a selector that compares values.map1
.fun main(args: Array<String>) {
val map1 = mapOf("key1" to 1, "key2" to 2, "key3" to 3)
val result = map1.maxByOrNull { it.value }
println(result)
}
key3=3
In this example,
map2
with key-value pairs.maxByOrNull()
function on map2
, applying a selector that compares keys.map2
.fun main(args: Array<String>) {
val map2 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val result = map2.maxByOrNull { it.key }
println(result)
}
cherry=3
In this example,
map3
with key-value pairs.maxByOrNull()
function on map3
, applying a selector that compares key lengths.map3
.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val result = map3.maxByOrNull { it.key.length }
println(result)
}
banana=2
In this Kotlin tutorial, we learned about maxByOrNull() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.