The syntax of Map.minOfWithOrNull() extension function is:
fun <K, V, R> Map<out K, V>.minOfWithOrNull( comparator: Comparator<in R>, selector: (Entry<K, V>) -> R ): R?
This minOfWithOrNull() 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 or null if there are no entries.
In this example,
map1
containing integer keys and character values.minOfWithOrNull()
function on map1
, using a custom comparator to compare values.map1
based on character values is returned.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val result = map1.minOfWithOrNull(Comparator { entry1, entry2 -> entry1.compareTo(entry2) }) { it.key }
println(result)
}
1
In this example,
map2
containing string keys and integer values.minOfWithOrNull()
function on map2
, using a custom comparator to compare values.map2
based on integer values is returned.fun main(args: Array<String>) {
val map2 = mapOf("apple" to 10, "banana" to 20, "cherry" to 30)
val result = map2.minOfWithOrNull(Comparator { entry1, entry2 -> entry1.compareTo(entry2) }) { it.value }
println(result)
}
10
In this Kotlin tutorial, we learned about minOfWithOrNull() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.