Kotlin Tutorials

Kotlin Map maxOfWith()
Syntax & Examples

Syntax of Map.maxOfWith()

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

fun <K, V, R> Map<out K, V>.maxOfWith( comparator: Comparator<in R>, selector: (Entry<K, V>) -> R ): R

This maxOfWith() extension function of Map returns the largest value according to the provided comparator among all values produced by selector function applied to each entry in the map.



✐ Examples

1 Get key with the longest string value

In this example,

  • We create a map named map1 with key-value pairs {'apple': 3, 'banana': 1, 'cherry': 2}.
  • We then apply the maxOfWith() function on map1, using the comparator compareBy { it.length } to compare keys based on their lengths.
  • As a result, the key with the longest string value ('banan') is returned.
  • We print the result to standard output.

Kotlin Program

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

Output

banana

2 Get key with the largest value

In this example,

  • We create a map named map2 with key-value pairs {1: 'apple', 2: 'banana', 3: 'cherry'}.
  • We then apply the maxOfWith() function on map2, using the comparator compareBy { it } to compare the keys.
  • As a result, the key which is the largest (3) is returned.
  • We print the result to standard output.

Kotlin Program

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

Output

3

Summary

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