Kotlin List minOfWithOrNull()
Syntax & Examples


Syntax of List.minOfWithOrNull()

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

fun <T, R> Iterable<T>.minOfWithOrNull( comparator: Comparator<in R>, selector: (T) -> R ): R?

This minOfWithOrNull() extension function of List returns the smallest value according to the provided comparator 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 of doubles named list containing elements 3.5, 1.2, 7.8, 4.3, 5.1.
  • We use the minOfWithOrNull() function with a comparator that compares elements directly and 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.5, 1.2, 7.8, 4.3, 5.1)
    val min = list.minOfWithOrNull(Comparator { a, b -> a.compareTo(b) }, { it })
    println("Minimum value: \$min")
}

Output

Minimum value: 1.2

2 Example

In this example,

  • We create a list of characters named list containing elements 'a', 'b', 'c'.
  • We use the minOfWithOrNull() function with a comparator that converts characters to integers for comparison and a selector that converts characters to integers.
  • 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.minOfWithOrNull(Comparator { a, b -> a.toInt().compareTo(b.toInt()) }, { 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 minOfWithOrNull() function with a comparator that compares string lengths and a selector that returns each string.
  • 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.minOfWithOrNull(Comparator { a, b -> a.length.compareTo(b.length) }, { it })
    println("Minimum value: \$min")
}

Output

Minimum value: apple

Summary

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