Kotlin List minOf()
Syntax & Examples
Syntax of List.minOf()
The syntax of List.minOf() extension function is:
fun <T> Iterable<T>.minOf(selector: (T) -> Double): Double
This minOf() extension function of List returns the smallest value 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
minOf()
function with 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.minOf { 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
minOf()
function with 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.minOf { it.toInt() }
println("Minimum value: \$min")
}
Output
Minimum value: 97
3 Example
In this example,
- We create a list of strings named
list
containing elements"apple", "banana", "cherry"
. - We use the
minOf()
function with 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.minOf { it.length }
println("Minimum value: \$min")
}
Output
Minimum value: 5
Summary
In this Kotlin tutorial, we learned about minOf() extension function of List: the syntax and few working examples with output and detailed explanation for each example.