Kotlin Map maxByOrNull()
Syntax & Examples


Syntax of Map.maxByOrNull()

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.



✐ Examples

1 Get entry with largest value in the map

In this example,

  • We create a map named map1 with key-value pairs.
  • We use the maxByOrNull() function on map1, applying a selector that compares values.
  • The resulting entry is the one with the largest value in map1.
  • We print the resulting entry 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.maxByOrNull { it.value }
    println(result)
}

Output

key3=3

2 Get entry with largest key in the map

In this example,

  • We create a map named map2 with key-value pairs.
  • We use the maxByOrNull() function on map2, applying a selector that compares keys.
  • The resulting entry is the one with the largest key in map2.
  • We print the resulting entry 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.maxByOrNull { it.key }
    println(result)
}

Output

cherry=3

3 Get entry with longest key in the map

In this example,

  • We create a map named map3 with key-value pairs.
  • We use the maxByOrNull() function on map3, applying a selector that compares key lengths.
  • The resulting entry is the one with the longest key in map3.
  • We print the resulting entry to standard output.

Kotlin Program

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

Output

banana=2

Summary

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.