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>): TThis 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
listcontaining the numbers[3, 1, 4, 1, 5, 9, 2]. - We find the minimum element in the list using the
minWithfunction and a comparator that compares elements directly. - The minimum element,
1, is stored inmin. - Finally, we print the value of
minto standard output using theprintlnfunction.
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
listcontaining the characters['x', 'a', 'b', 'c']. - We find the minimum element in the list using the
minWithfunction and a comparator that compares characters directly. - The minimum element,
'a', is stored inmin. - Finally, we print the value of
minto standard output using theprintlnfunction.
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
listcontaining the strings['apple', 'banana', 'orange', 'grape']. - We find the minimum element in the list using the
minWithfunction and a comparator that compares strings lexically. - The minimum element,
'apple', is stored inmin. - Finally, we print the value of
minto standard output using theprintlnfunction.
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.