Kotlin Map maxWith()
Syntax & Examples
Syntax of Map.maxWith()
There are 2 variations for the syntax of Map.maxWith() extension function. They are:
1.
fun <K, V> Map<out K, V>.maxWith( comparator: Comparator<in Entry<K, V>> ): Entry<K, V>
This extension function returns the first entry having the largest value according to the provided comparator.
2.
fun <K, V> Map<out K, V>.maxWith( comparator: Comparator<in Entry<K, V>> ): Entry<K, V>?
This extension function
✐ Examples
1 Get entry with the largest value
In this example,
- We create a map named
map1
with key-value pairs{'apple': 3, 'banana': 1, 'cherry': 2}
. - We then apply the
maxWith()
function onmap1
, using the comparatorcompareBy { it.value }
to compare entries based on their values. - As a result, the entry with the largest value ('apple': 3) 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.maxWith(compareBy { it.value })
println(result)
}
Output
apple=3
2 Get entry with the largest key
In this example,
- We create a map named
map2
with key-value pairs{1: 'apple', 2: 'banana', 3: 'cherry'}
. - We then apply the
maxWith()
function onmap2
, using the comparatorcompareBy { it.key }
to compare entries based on their keys. - As a result, the entry with the largest key (3: 'cherry') 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.maxWith(compareBy { it.key })
println(result)
}
Output
3=cherry
3 Get entry with the largest numeric value
In this example,
- We create a map named
map3
with key-value pairs{'apple': 5, 'banana': 7, 'cherry': 3}
. - We then apply the
maxWith()
function onmap3
, using the comparatorcompareBy { it.value }
to compare entries based on their values. - As a result, the entry with the largest numeric value ('banana': 7) is returned.
- We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf("apple" to 5, "banana" to 7, "cherry" to 3)
val result = map3.maxWith(compareBy { it.value })
println(result)
}
Output
banana=7
Summary
In this Kotlin tutorial, we learned about maxWith() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.