Kotlin List maxOfWithOrNull()
Syntax & Examples
Syntax of List.maxOfWithOrNull()
The syntax of List.maxOfWithOrNull() extension function is:
fun <T, R> Iterable<T>.maxOfWithOrNull( comparator: Comparator<in R>, selector: (T) -> R ): R?
This maxOfWithOrNull() extension function of List returns the largest value according to the provided comparator 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 numbers[3, 1, 4, 1, 5, 9, 2, 6]
. - We apply
maxOfWithOrNull()
function with a custom comparator to find the maximum value. - The selector function
{ it }
returns each element as it is. - Since the list is not empty, the maximum value is determined using the comparator.
- The maximum value, which is
9
, is stored inresult
. - Finally, we print the value of
result
to standard output using theprint
statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(3, 1, 4, 1, 5, 9, 2, 6);
val result = list.maxOfWithOrNull(Comparator.comparing { it }) { it };
print(result);
}
Output
9
2 Example
In this example,
- We create a list named
list
containing the characters['a', 'p', 'p', 'l', 'e']
. - We apply
maxOfWithOrNull()
function with the natural order comparator to find the maximum value. - The selector function
{ it }
returns each character as it is. - Since the list is not empty, the maximum value is determined using the natural order comparator.
- The maximum value, which is
'p'
, is stored inresult
. - Finally, we print the value of
result
to standard output using theprint
statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'p', 'p', 'l', 'e');
val result = list.maxOfWithOrNull(Comparator.naturalOrder()) { it };
print(result);
}
Output
p
3 Example
In this example,
- We create a list named
list
containing the strings['apple', 'banana', 'orange', 'grape']
. - We apply
maxOfWithOrNull()
function with a comparator based on the length of the strings to find the string with the maximum length. - The selector function
{ it }
returns each string as it is. - Since the list is not empty, the string with the maximum length is determined using the length-based comparator.
- The string with the maximum length, which is
'banana'
, is stored inresult
. - Finally, we print the value of
result
to standard output using theprint
statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "orange", "grape");
val result = list.maxOfWithOrNull(compareBy { it.length }) { it };
print(result);
}
Output
banana
Summary
In this Kotlin tutorial, we learned about maxOfWithOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.