Kotlin Map maxOfOrNull()
Syntax & Examples


Syntax of Map.maxOfOrNull()

The syntax of Map.maxOfOrNull() extension function is:

fun <K, V> Map<out K, V>.maxOfOrNull( selector: (Entry<K, V>) -> Double ): Double?

This maxOfOrNull() extension function of Map returns the largest value among all values produced by selector function applied to each entry in the map or null if there are no entries.



✐ Examples

1 Get largest value in the map

In this example,

  • We create a map named map1 with key-value pairs.
  • We use the maxOfOrNull() function on map1, applying a selector that gets the value of entry.
  • The resulting value is the largest among all values in map1.
  • We print the resulting value to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1 = mapOf("key1" to 1, "key2" to 2, "key3" to 3)
    val result = map1.maxOfOrNull { it.value }
    println(result)
}

Output

3

2 Get largest key length in the map

In this example,

  • We create a map named map2 with key-value pairs.
  • We use the maxOfOrNull() function on map2, applying a selector that takes key lengths.
  • The resulting value is the largest among all key lengths in map2.
  • We print the resulting value to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map2 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
    val result = map2.maxOfOrNull { it.key.length }
    println(result)
}

Output

6.0

Summary

In this Kotlin tutorial, we learned about maxOfOrNull() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.