Kotlin Map minOf()
Syntax & Examples
Syntax of Map.minOf()
The syntax of Map.minOf() extension function is:
fun <K, V> Map<out K, V>.minOf( selector: (Entry<K, V>) -> Double ): Double
This minOf() extension function of Map returns the smallest value 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
minOf()
function onmap1
with a selector based on values converted to Double. - 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.minOf { it.value.toDouble() }
println(result)
}
Output
1.0
2 Get smallest key length as Double in the map
In this example,
- We create a map named
map2
with key-value pairs. - We use the
minOf()
function onmap2
with a selector based on key lengths converted to Double. - The resulting value is the smallest key length as Double 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.minOf { it.key.length.toDouble() }
println(result)
}
Output
5.0
3 Get smallest key length as Double in the map
In this example,
- We create a map named
map3
with key-value pairs. - We use the
minOf()
function onmap3
with a selector based on key lengths converted to Double. - The resulting value is the smallest key length as Double in
map3
. - We print the resulting value 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.minOf { it.key.length.toDouble() }
println(result)
}
Output
3.0
Summary
In this Kotlin tutorial, we learned about minOf() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.