Kotlin List minByOrNull()
Syntax & Examples


Syntax of List.minByOrNull()

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

fun <T, R : Comparable<R>> Iterable<T>.minByOrNull( selector: (T) -> R ): T?

This minByOrNull() extension function of List returns the first element yielding the smallest value of the given function or null if there are no elements.



✐ Examples

1 Example

In this example,

  • We create a list of integers named list containing elements 3, 1, 7, 4, 5.
  • We use the minByOrNull() function with a selector that returns the elements themselves.
  • The minimum value in the list, min, is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(3, 1, 7, 4, 5)
    val min = list.minByOrNull { it }
    println("Minimum value: \$min")
}

Output

Minimum value: 1

2 Example

In this example,

  • We create a list of characters named list containing elements 'a', 'b', 'c'.
  • We use the minByOrNull() function with a selector that returns the elements themselves.
  • The minimum value in the list, min, is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'b', 'c')
    val min = list.minByOrNull { it }
    println("Minimum value: \$min")
}

Output

Minimum value: a

3 Example

In this example,

  • We create a list of strings named list containing elements "apple", "banana", "cherry".
  • We use the minByOrNull() function with a selector that returns the elements themselves.
  • The minimum value in the list, min, is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry")
    val min = list.minByOrNull { it }
    println("Minimum value: \$min")
}

Output

Minimum value: apple

Summary

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