Kotlin List maxWithOrNull()
Syntax & Examples


Syntax of List.maxWithOrNull()

The syntax of List.maxWithOrNull() extension function is:

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

This maxWithOrNull() extension function of List returns the first element having the largest value according to the provided comparator 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 maxWithOrNull() function with the natural order comparator to find the first element having the largest value.
  • Since the list is not empty, the first element having the largest value is determined using the natural order comparator.
  • The first element with the largest value, which is 9, is stored in result.
  • Finally, we print the value of result to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(3, 1, 4, 1, 5, 9, 2, 6);
    val result = list.maxWithOrNull(Comparator.naturalOrder());
    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 maxWithOrNull() function with the reverse order comparator to find the first element having the largest value.
  • Since the list is not empty, the first element having the largest value is determined using the reverse order comparator.
  • The first element with the largest value, which is 'a', is stored in result.
  • Finally, we print the value of result to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'p', 'p', 'l', 'e');
    val result = list.maxWithOrNull(Comparator.reverseOrder());
    print(result);
}

Output

a

3 Example

In this example,

  • We create a list named list containing the strings ['apple', 'banana', 'orange', 'grape'].
  • We apply maxWithOrNull() function with a comparator based on the length of the strings to find the first string with the largest length.
  • Since the list is not empty, the first string with the largest length is determined using the length-based comparator.
  • The first string with the largest length, which is 'banana', is stored in result.
  • Finally, we print the value of result to standard output using the print statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "orange", "grape");
    val result = list.maxWithOrNull(compareBy { it.length });
    print(result);
}

Output

banana

Summary

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