The syntax of Map.minWithOrNull() extension function is:
fun <K, V> Map<out K, V>.minWithOrNull( comparator: Comparator<in Entry<K, V>> ): Entry<K, V>?
This minWithOrNull() extension function of Map returns the first entry having the smallest value according to the provided comparator or null if there are no entries.
In this example,
map1
containing key-value pairs 1 to 'a'
, 2 to 'b'
, and 3 to 'c'
.minWithOrNull()
function on map1
, using a comparator based on values to find the entry with the smallest value.map1
is returned.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c');
val result = map1.minWithOrNull(compareBy { it.value });
print(result);
}
1=a
In this example,
map2
containing key-value pairs 'a' to 1
, 'b' to 2
, and 'c' to 3
.minWithOrNull()
function on map2
, using a comparator based on keys to find the entry with the smallest key.map2
is returned.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3);
val result = map2.minWithOrNull(compareBy { it.key });
print(result);
}
a=1
In this example,
map3
containing key-value pairs 1 to "apple"
, 2 to "banana"
, and 3 to "cherry"
.minWithOrNull()
function on map3
, using a comparator based on the lengths of values to find the entry with the shortest value.map3
is returned.fun main(args: Array<String>) {
val map3 = mapOf(1 to "apple", 2 to "banana", 3 to "cherry");
val result = map3.minWithOrNull(compareBy { it.value.length });
print(result);
}
1=apple
In this Kotlin tutorial, we learned about minWithOrNull() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.