Kotlin List minWithOrNull()
Syntax & Examples


Syntax of List.minWithOrNull()

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

fun <T> Iterable<T>.minWithOrNull( comparator: Comparator<in T> ): T?

This minWithOrNull() extension function of List returns the first element having the smallest value according to the provided comparator or null if there are no elements.



✐ Examples

1 Example

In this example,

  • We create a list of integers named list containing elements 5, 3, 9, 2, 7.
  • We use the minWithOrNull() function with a comparator that compares elements using compareTo() method.
  • The smallest element in the list, according to the comparator, is stored in smallestElement.
  • The value of smallestElement is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(5, 3, 9, 2, 7)
    val smallestElement = list.minWithOrNull(Comparator { a, b -> a.compareTo(b) })
    println(smallestElement)
}

Output

2

2 Example

In this example,

  • We create a list of characters named list containing elements 'd', 'b', 'g', 'a'.
  • We use the minWithOrNull() function with a comparator that compares elements using compareTo() method.
  • The smallest element in the list, according to the comparator, is stored in smallestElement.
  • The value of smallestElement is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('d', 'b', 'g', 'a')
    val smallestElement = list.minWithOrNull(Comparator { a, b -> a.compareTo(b) })
    println(smallestElement)
}

Output

97

3 Example

In this example,

  • We create a list of strings named list containing elements "apple", "banana", "cherry".
  • We use the minWithOrNull() function with a comparator that compares elements using compareTo() method.
  • The smallest element in the list, according to the comparator, is stored in smallestElement.
  • The value of smallestElement is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry")
    val smallestElement = list.minWithOrNull(Comparator { a, b -> a.compareTo(b) })
    println(smallestElement)
}

Output

apple

Summary

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