The syntax of Map.maxOf() extension function is:
fun <K, V> Map<out K, V>.maxOf( selector: (Entry<K, V>) -> Double ): Double
This maxOf() extension function of Map returns the largest value among all values produced by selector function applied to each entry in the map.
In this example,
map1
containing integer keys and double values.maxOf()
function on map1
, using the selector { it.value }
to extract the values.map1
is returned.fun main(args: Array<String>) {
val map1 = mapOf(1 to 10.5, 2 to 20.3, 3 to 30.8)
val result = map1.maxOf { it.value }
println(result)
}
30.8
In this example,
map2
containing string keys and double values.maxOf()
function on map2
, using the selector { it.value }
to extract the values.map2
is returned.fun main(args: Array<String>) {
val map2 = mapOf("apple" to 3.14, "banana" to 1.618, "cherry" to 2.718)
val result = map2.maxOf { it.value }
println(result)
}
3.14
In this example,
map3
containing string keys and double values.maxOf()
function on map3
, using the selector { it.value }
to extract the values.map3
is returned.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 5.2, "banana" to 4.1, "cherry" to 6.3)
val result = map3.maxOf { it.value }
println(result)
}
6.3
In this Kotlin tutorial, we learned about maxOf() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.