Kotlin Tutorials

Kotlin Map minWithOrNull()
Syntax & Examples

Syntax of Map.minWithOrNull()

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.



✐ Examples

1 Get entry with smallest value in map

In this example,

  • We create a map named map1 containing key-value pairs 1 to 'a', 2 to 'b', and 3 to 'c'.
  • We then apply the minWithOrNull() function on map1, using a comparator based on values to find the entry with the smallest value.
  • As a result, the entry with the smallest value in map1 is returned.
  • We print the result to standard output.

Kotlin Program

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);
}

Output

1=a

2 Get entry with smallest key in map

In this example,

  • We create a map named map2 containing key-value pairs 'a' to 1, 'b' to 2, and 'c' to 3.
  • We then apply the minWithOrNull() function on map2, using a comparator based on keys to find the entry with the smallest key.
  • As a result, the entry with the smallest key in map2 is returned.
  • We print the result to standard output.

Kotlin Program

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);
}

Output

a=1

3 Get entry with shortest value in map

In this example,

  • We create a map named map3 containing key-value pairs 1 to "apple", 2 to "banana", and 3 to "cherry".
  • We then apply the minWithOrNull() function on map3, using a comparator based on the lengths of values to find the entry with the shortest value.
  • As a result, the entry with the shortest value in map3 is returned.
  • We print the result to standard output.

Kotlin Program

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);
}

Output

1=apple

Summary

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.