Kotlin Tutorials

Kotlin Map minOfOrNull()
Syntax & Examples

Syntax of Map.minOfOrNull()

The syntax of Map.minOfOrNull() extension function is:

fun <K, V> Map<out K, V>.minOfOrNull( selector: (Entry<K, V>) -> Double ): Double?

This minOfOrNull() extension function of Map returns the smallest value among all values produced by selector function applied to each entry in the map or null if there are no entries.



✐ Examples

1 Get smallest numeric value in the map

In this example,

  • We create a map named map1 with key-value pairs {'apple': 3, 'banana': 1, 'cherry': 2}.
  • We then apply the minOfOrNull() function on map1, converting the values to doubles using toDouble(), to compare numeric values.
  • As a result, the smallest numeric value (1) is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1 = mapOf("apple" to 3, "banana" to 1, "cherry" to 2)
    val result = map1.minOfOrNull { it.value.toDouble() }
    println(result)
}

Output

1.0

2 Get smallest numeric key in the map

In this example,

  • We create a map named map2 with key-value pairs {1: 'apple', 2: 'banana', 3: 'cherry'}.
  • We then apply the minOfOrNull() function on map2, converting the keys to doubles using toDouble(), to compare numeric keys.
  • As a result, the smallest numeric key (1) is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map2 = mapOf(1 to "apple", 2 to "banana", 3 to "cherry")
    val result = map2.minOfOrNull { it.key.toDouble() }
    println(result)
}

Output

1.0

3 Get smallest numeric value in the map

In this example,

  • We create a map named map3 with key-value pairs {'apple': 5, 'banana': 7, 'cherry': 3}.
  • We then apply the minOfOrNull() function on map3, converting the values to doubles using toDouble(), to compare numeric values.
  • As a result, the smallest numeric value (3) is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map3 = mapOf("apple" to 5, "banana" to 7, "cherry" to 3)
    val result = map3.minOfOrNull { it.value.toDouble() }
    println(result)
}

Output

3.0

Summary

In this Kotlin tutorial, we learned about minOfOrNull() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.