Kotlin Tutorials

Kotlin Map minOfWithOrNull()
Syntax & Examples

Syntax of Map.minOfWithOrNull()

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.



✐ Examples

1 Get minimum key in the map based on character values

In this example,

  • We create a map named map1 containing integer keys and character values.
  • We then apply the minOfWithOrNull() function on map1, using a custom comparator to compare values.
  • As a result, the minimum key in map1 based on character values 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.minOfWithOrNull(Comparator { entry1, entry2 -> entry1.compareTo(entry2) }) { it.key }
    println(result)
}

Output

1

2 Get minimum value in the map based on integer keys

In this example,

  • We create a map named map2 containing string keys and integer values.
  • We then apply the minOfWithOrNull() function on map2, using a custom comparator to compare values.
  • As a result, the minimum value in map2 based on integer values is returned.
  • We print the result to standard output.

Kotlin Program

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

Output

10

Summary

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.