Kotlin List maxOfOrNull()
Syntax & Examples
Syntax of List.maxOfOrNull()
The syntax of List.maxOfOrNull() extension function is:
fun <T> Iterable<T>.maxOfOrNull( selector: (T) -> Double ): Double?
This maxOfOrNull() extension function of List returns the largest value among all values produced by selector function applied to each element in the collection or null if there are no elements.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing the doubles10.5, 20.3, 15.8, 30.1
. - We apply the
maxOfOrNull
function tolist
, which takes a lambda with one parameter:it
. - Within the lambda,
it
represents each element of the list. - The lambda simply returns each element as is.
- The
maxOfOrNull
function returns the largest value among all values produced by the lambda. - Finally, we print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(10.5, 20.3, 15.8, 30.1);
val result = list.maxOfOrNull { it }
print(result);
}
Output
30.1
2 Example
In this example,
- We create a list named
list
containing the strings'a', 'b', 'c'
. - We apply the
maxOfOrNull
function tolist
, which takes a lambda with one parameter:it
. - Within the lambda,
it
represents each element of the list. - We convert each character to its length as a double.
- The
maxOfOrNull
function returns the largest length among all strings in the list. - Finally, we print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("a", "b", "c");
val result = list.maxOfOrNull { it.length.toDouble() }
print(result);
}
Output
1.0
3 Example
In this example,
- We create a list named
list
containing the strings'apple', 'banana', 'cherry'
. - We apply the
maxOfOrNull
function tolist
, which takes a lambda with one parameter:it
. - Within the lambda,
it
represents each element of the list. - We convert each string to its length as a double.
- The
maxOfOrNull
function returns the largest length among all strings in the list. - Finally, we print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry");
val result = list.maxOfOrNull { it.length.toDouble() }
print(result);
}
Output
6.0
Summary
In this Kotlin tutorial, we learned about maxOfOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.