Kotlin List maxByOrNull()
Syntax & Examples


Syntax of List.maxByOrNull()

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

fun <T, R : Comparable<R>> Iterable<T>.maxByOrNull( selector: (T) -> R ): T?

This maxByOrNull() extension function of List returns the first element yielding the largest value of the given function or null if there are no elements.



✐ Examples

1 Get largest number in the list

In this example,

  • We create a list named list1 containing the integers 1, 2, 3.
  • We then apply the maxByOrNull() function on list1, using the identity selector { it } to compare elements directly.
  • As a result, the largest element in list1 is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(1, 2, 3);
    val result = list1.maxByOrNull { it }
    print(result);
}

Output

3

2 Get character with largest Unicode value in the list

In this example,

  • We create a list named list2 containing the strings 'a', 'b', 'c'.
  • We then apply the maxByOrNull() function on list2, using the identity selector { it } to compare elements directly.
  • As a result, the string with the largest Unicode value is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list2 = listOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);
    val result = list2.maxByOrNull { it }
    print(result);
}

Output

c

3 Get longest string in the list

In this example,

  • We create a list named list3 containing the strings 'apple', 'banana', 'cherry'.
  • We then apply the maxByOrNull() function on list3, using the selector { it.length } to compare elements based on their lengths.
  • As a result, the longest string in list3 is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list3 = listOf(&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;);
    val result = list3.maxByOrNull { it.length }
    print(result);
}

Output

banana

Summary

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