The syntax of Map.maxWithOrNull() extension function is:
fun <K, V> Map<out K, V>.maxWithOrNull( comparator: Comparator<in Entry<K, V>> ): Entry<K, V>?
This maxWithOrNull() extension function of Map returns the first entry having the largest value according to the provided comparator or null if there are no entries.
In this example,
map1
with key-value pairs.maxWithOrNull()
function on map1
with a comparator based on values.map1
.fun main(args: Array<String>) {
val map1 = mapOf("key1" to 1, "key2" to 2, "key3" to 3)
val result = map1.maxWithOrNull(compareBy { it.value })
println(result)
}
key3=3
In this example,
map2
with key-value pairs.maxWithOrNull()
function on map2
with a comparator based on key lengths.map2
.fun main(args: Array<String>) {
val map2 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val result = map2.maxWithOrNull(compareBy { it.key.length })
println(result)
}
banana=2
In this example,
map3
with key-value pairs.maxWithOrNull()
function on map3
with a comparator based on keys. The key strings are compared lexicographically.map3
based on english dictionary.fun main(args: Array<String>) {
val map3 = mapOf("one" to 1, "two" to 2, "three" to 3)
val result = map3.maxWithOrNull(compareBy { it.key.toDouble() })
println(result)
}
two=2
In this Kotlin tutorial, we learned about maxWithOrNull() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.