Kotlin List minWith()
Syntax & Examples


Syntax of List.minWith()

There are 2 variations for the syntax of List.minWith() extension function. They are:

1.
fun <T> Iterable<T>.minWith(comparator: Comparator<in T>): T

This extension function returns the first element having the smallest value according to the provided comparator.

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

This extension function



✐ Examples

1 Example

In this example,

  • We create a list named list containing the numbers [3, 1, 4, 1, 5, 9, 2].
  • We find the minimum element in the list using the minWith function and a comparator that compares elements directly.
  • The minimum element, 1, is stored in min.
  • Finally, we print the value of min to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(3, 1, 4, 1, 5, 9, 2);
    val min = list.minWith(compareBy { it });
    println(min);
}

Output

1

2 Example

In this example,

  • We create a list named list containing the characters ['x', 'a', 'b', 'c'].
  • We find the minimum element in the list using the minWith function and a comparator that compares characters directly.
  • The minimum element, 'a', is stored in min.
  • Finally, we print the value of min to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('x', 'a', 'b', 'c');
    val min = list.minWith(compareBy { it });
    println(min);
}

Output

a

3 Example

In this example,

  • We create a list named list containing the strings ['apple', 'banana', 'orange', 'grape'].
  • We find the minimum element in the list using the minWith function and a comparator that compares strings lexically.
  • The minimum element, 'apple', is stored in min.
  • Finally, we print the value of min to standard output using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "orange", "grape");
    val min = list.minWith(compareBy { it });
    println(min);
}

Output

apple

Summary

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