Kotlin List maxOf()
Syntax & Examples
Syntax of List.maxOf()
The syntax of List.maxOf() extension function is:
fun <T> Iterable<T>.maxOf(selector: (T) -> Double): Double
This maxOf() extension function of List returns the largest 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 elements1.5, 2.5, 3.5, 4.5, 5.5
. - We use the
maxOf()
function with a selector function that returns the element itself. - The maximum value in the list,
max
, is printed to standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1.5, 2.5, 3.5, 4.5, 5.5)
val max = list.maxOf { it }
println("Maximum value: \$max")
}
Output
Maximum value: 5.5
2 Example
In this example,
- We create a list of characters named
list
containing elements'a', 'b', 'c'
. - We use the
maxOf()
function with a selector function that converts each character to its ASCII value. - The maximum value in the list,
max
, is printed to standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c')
val max = list.maxOf { it.toInt() }
println("Maximum value: \$max")
}
Output
Maximum value: 99
3 Example
In this example,
- We create a list of strings named
list
containing elements"apple", "banana", "cherry"
. - We use the
maxOf()
function with a selector function that returns the length of each string. - The maximum value in the list,
max
, is printed to standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry")
val max = list.maxOf { it.length }
println("Maximum value: \$max")
}
Output
Maximum value: 6
Summary
In this Kotlin tutorial, we learned about maxOf() extension function of List: the syntax and few working examples with output and detailed explanation for each example.