0
0
KotlinHow-ToBeginner · 3 min read

How to Find Max in List Kotlin: Simple Examples and Tips

In Kotlin, you can find the maximum value in a list using the maxOrNull() function, which returns the largest element or null if the list is empty. For example, val max = list.maxOrNull() gives you the max value safely.
📐

Syntax

The main function to find the maximum value in a Kotlin list is maxOrNull(). It returns the largest element or null if the list is empty.

Usage:

  • list.maxOrNull(): Returns the max element or null.
kotlin
val list = listOf(3, 7, 2, 9, 5)
val maxValue = list.maxOrNull()
💻

Example

This example shows how to find the maximum number in a list of integers using maxOrNull(). It also handles the case when the list is empty.

kotlin
fun main() {
    val numbers = listOf(10, 25, 7, 30, 18)
    val maxNumber = numbers.maxOrNull()

    if (maxNumber != null) {
        println("The maximum number is: $maxNumber")
    } else {
        println("The list is empty.")
    }
}
Output
The maximum number is: 30
⚠️

Common Pitfalls

One common mistake is using max() which is deprecated and can cause errors. Another is not handling empty lists, which makes maxOrNull() return null. Always check for null before using the result.

kotlin
fun main() {
    val emptyList = listOf<Int>()

    // Wrong: max() is deprecated and unsafe
    // val maxValue = emptyList.max() // This will cause a compile warning or error

    // Right: use maxOrNull() and check for null
    val maxValue = emptyList.maxOrNull()
    if (maxValue == null) {
        println("List is empty, no max value.")
    } else {
        println("Max value is $maxValue")
    }
}
Output
List is empty, no max value.
📊

Quick Reference

FunctionDescription
maxOrNull()Returns the maximum element or null if the list is empty.
maxByOrNull(selector)Returns the element with the max value according to selector function or null if empty.
max()Deprecated. Avoid using this function.

Key Takeaways

Use maxOrNull() to safely find the maximum value in a Kotlin list.
Always check if the result of maxOrNull() is null to handle empty lists.
Avoid using the deprecated max() function.
You can use maxByOrNull() to find max based on a property or custom selector.