The syntax of Map.minByOrNull() extension function is:
fun <K, V, R : Comparable<R>> Map<out K, V>.minByOrNull( selector: (Entry<K, V>) -> R ): Entry<K, V>?
This minByOrNull() extension function of Map returns the first entry yielding the smallest value of the given function or null if there are no entries.
In this example,
map1
with key-value pairs {'apple': 3, 'banana': 1, 'cherry': 2}
.minByOrNull()
function on map1
, using the selector { it.value }
to compare entries based on their values.fun main(args: Array<String>) {
val map1 = mapOf("apple" to 3, "banana" to 1, "cherry" to 2)
val result = map1.minByOrNull { it.value }
println(result)
}
banana=1
In this example,
map2
with key-value pairs {1: 'apple', 2: 'banana', 3: 'cherry'}
.minByOrNull()
function on map2
, using the selector { it.key }
to compare entries based on their keys.fun main(args: Array<String>) {
val map2 = mapOf(1 to "apple", 2 to "banana", 3 to "cherry")
val result = map2.minByOrNull { it.key }
println(result)
}
1=apple
In this example,
map3
with key-value pairs {'apple': 5, 'banana': 7, 'cherry': 3}
.minByOrNull()
function on map3
, using the selector { it.value }
to compare entries based on their values.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 5, "banana" to 7, "cherry" to 3)
val result = map3.minByOrNull { it.value }
println(result)
}
cherry=3
In this Kotlin tutorial, we learned about minByOrNull() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.