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.
In this example,
map1
with key-value pairs {'apple': 3, 'banana': 1, 'cherry': 2}
.maxOfWith()
function on map1
, using the comparator compareBy { it.length }
to compare keys based on their lengths.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)
}
banana
In this example,
map2
with key-value pairs {1: 'apple', 2: 'banana', 3: 'cherry'}
.maxOfWith()
function on map2
, using the comparator compareBy { it }
to compare the keys.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)
}
3
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.