Kotlin List minOfOrNull()
Syntax & Examples


Syntax of List.minOfOrNull()

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

fun <T> Iterable<T>.minOfOrNull( selector: (T) -> Double ): Double?

This minOfOrNull() extension function of List returns the smallest value among all values produced by selector function applied to each element in the collection or null if there are no elements.



✐ Examples

1 Example

In this example,

  • We create a list named list containing the numbers [3, 1, 4, 1, 5, 9, 2, 6].
  • We apply minOfOrNull() function with a selector function that converts each element to a Double.
  • Since the list is not empty, the smallest value produced by the selector function is determined.
  • The smallest value, which is 1.0, is stored in result.
  • Finally, we print the value of result to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(3, 1, 4, 1, 5, 9, 2, 6);
    val result = list.minOfOrNull { it.toDouble() };
    print(result);
}

Output

1.0

2 Example

In this example,

  • We create a list named list containing the characters ['a', 'p', 'p', 'l', 'e'].
  • We apply minOfOrNull() function with a selector function that converts each character to its ASCII value and then to Double.
  • Since the list is not empty, the smallest value produced by the selector function is determined.
  • The smallest value, which is 97.0 (ASCII value of 'a'), is stored in result.
  • Finally, we print the value of result to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'p', 'p', 'l', 'e');
    val result = list.minOfOrNull { it.toInt().toDouble() };
    print(result);
}

Output

97.0

3 Example

In this example,

  • We create a list named list containing the strings ['apple', 'banana', 'orange', 'grape'].
  • We apply minOfOrNull() function with a selector function that converts each string to its length as Double.
  • Since the list is not empty, the smallest value produced by the selector function is determined.
  • The smallest value, which is 5.0 (length of 'apple'), is stored in result.
  • Finally, we print the value of result to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "orange", "grape");
    val result = list.minOfOrNull { it.length.toDouble() };
    print(result);
}

Output

5.0

Summary

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