Kotlin List maxWith()
Syntax & Examples


Syntax of List.maxWith()

There are 2 variations for the syntax of List.maxWith() extension function. They are:

1.
fun <T> Iterable<T>.maxWith(comparator: Comparator<in T>): T

This extension function returns the first element having the largest value according to the provided comparator.

2.
fun <T> Iterable<T>.maxWith(comparator: Comparator<in T>): T?

This extension function



✐ Examples

1 Example

In this example,

  • We create a list of integers named list containing elements 3, 1, 7, 4, 5.
  • We use the maxWith() function with a comparator that sorts the elements in ascending order.
  • 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.maxWith(compareBy { 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 maxWith() function with a comparator that sorts the elements based on their ASCII values.
  • 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.maxWith(compareBy { 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 maxWith() function with a comparator that sorts the elements based on their natural ordering.
  • 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.maxWith(compareBy { it })
    println("Maximum value: \$max")
}

Output

Maximum value: cherry

Summary

In this Kotlin tutorial, we learned about maxWith() extension function of List: the syntax and few working examples with output and detailed explanation for each example.