Kotlin Tutorials

Kotlin Map maxOf()
Syntax & Examples

Syntax of Map.maxOf()

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.



✐ Examples

1 Get maximum value from a map of integers to doubles

In this example,

  • We create a map named map1 containing integer keys and double values.
  • We then apply the maxOf() function on map1, using the selector { it.value } to extract the values.
  • As a result, the maximum value among all the double values in map1 is returned.
  • We print the result to standard output.

Kotlin Program

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)
}

Output

30.8

2 Get maximum value from a map of strings to doubles

In this example,

  • We create a map named map2 containing string keys and double values.
  • We then apply the maxOf() function on map2, using the selector { it.value } to extract the values.
  • As a result, the maximum value among all the double values in map2 is returned.
  • We print the result to standard output.

Kotlin Program

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)
}

Output

3.14

3 Get maximum value from a map of strings to doubles

In this example,

  • We create a map named map3 containing string keys and double values.
  • We then apply the maxOf() function on map3, using the selector { it.value } to extract the values.
  • As a result, the maximum value among all the double values in map3 is returned.
  • We print the result to standard output.

Kotlin Program

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)
}

Output

6.3

Summary

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.