Kotlin Map maxWithOrNull()
Syntax & Examples


Syntax of Map.maxWithOrNull()

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.



✐ 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 maxWithOrNull() function on map1 with a comparator based on 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.maxWithOrNull(compareBy { it.value })
    println(result)
}

Output

key3=3

2 Get entry with largest key length in the map

In this example,

  • We create a map named map2 with key-value pairs.
  • We use the maxWithOrNull() function on map2 with a comparator based on key lengths.
  • The resulting entry is the one with the largest key length 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.maxWithOrNull(compareBy { it.key.length })
    println(result)
}

Output

banana=2

3 Get entry with largest key lexicographically in the map

In this example,

  • We create a map named map3 with key-value pairs.
  • We use the maxWithOrNull() function on map3 with a comparator based on keys. The key strings are compared lexicographically.
  • The resulting entry is the one with the largest value in map3 based on english dictionary.
  • We print the resulting entry to standard output.

Kotlin Program

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

Output

two=2

Summary

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.