Kotlin Map minOfWith()
Syntax & Examples
Syntax of Map.minOfWith()
The syntax of Map.minOfWith() extension function is:
fun <K, V, R> Map<out K, V>.minOfWith( comparator: Comparator<in R>, selector: (Entry<K, V>) -> R ): R
This minOfWith() extension function of Map returns the smallest value according to the provided comparator among all values produced by selector function applied to each entry in the map.
✐ Examples
1 Get smallest value in the map
In this example,
- We create a map named
map1
with key-value pairs. - We use the
minOfWith()
function onmap1
with a custom comparator comparing values. - The resulting value is the smallest among all values in
map1
. - We print the resulting value 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.minOfWith(Comparator { o1, o2 -> o1.compareTo(o2) }, { it.value })
println(result)
}
Output
1
2 Get smallest key length in the map
In this example,
- We create a map named
map2
with key-value pairs. - We use the
minOfWith()
function onmap2
with a custom comparator comparing key lengths. - The resulting value is the smallest key length in
map2
. - We print the resulting value 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.minOfWith(Comparator { o1, o2 -> o1.compareTo(o2) }, { it.key.length })
println(result)
}
Output
5
Summary
In this Kotlin tutorial, we learned about minOfWith() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.