Kotlin List maxOfWith()
Syntax & Examples
Syntax of List.maxOfWith()
The syntax of List.maxOfWith() extension function is:
fun <T, R> Iterable<T>.maxOfWith( comparator: Comparator<in R>, selector: (T) -> R ): R
This maxOfWith() 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.
✐ Examples
1 Example
In this example,
- We create a list of integers named
list
containing elements3, 1, 7, 4, 5
. - We use the
maxOfWith()
function with a comparator that sorts the elements in ascending order and 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(3, 1, 7, 4, 5)
val max = list.maxOfWith(compareBy { it }, { it })
println("Maximum value: \$max")
}
Output
Maximum value: 7
2 Example
In this example,
- We create a list of characters named
list
containing elements'a', 'b', 'c'
. - We use the
maxOfWith()
function with a comparator that sorts the elements based on their ASCII values and 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('a', 'b', 'c')
val max = list.maxOfWith(compareBy { it.toInt() }, { it })
println("Maximum value: \$max")
}
Output
Maximum value: c
3 Example
In this example,
- We create a list of strings named
list
containing elements"apple", "banana", "cherry"
. - We use the
maxOfWith()
function with a comparator that sorts the elements based on their lengths and 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("apple", "banana", "cherry")
val max = list.maxOfWith(compareBy { it.length }, { it })
println("Maximum value: \$max")
}
Output
Maximum value: banana
Summary
In this Kotlin tutorial, we learned about maxOfWith() extension function of List: the syntax and few working examples with output and detailed explanation for each example.