Kotlin List minOfWith()
Syntax & Examples
Syntax of List.minOfWith()
The syntax of List.minOfWith() extension function is:
fun <T, R> Iterable<T>.minOfWith( comparator: Comparator<in R>, selector: (T) -> R ): R
This minOfWith() 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.
✐ Examples
1 Example
In this example,
- We create a list of doubles named
list
containing elements3.5, 1.2, 7.8, 4.3, 5.1
. - We use the
minOfWith()
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.minOfWith(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
minOfWith()
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.minOfWith(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
minOfWith()
function with a comparator that compares string lengths and a selector that returns the length of 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.minOfWith(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 minOfWith() extension function of List: the syntax and few working examples with output and detailed explanation for each example.