Kotlin max value in the list
Video: Kotlin max value in the list by Taught by Celeste AI - AI Coding Coach
Watch full page →Kotlin: Finding the Maximum Value in a List
In Kotlin, finding the maximum value in a list is straightforward using built-in functions. This example demonstrates how to use the maxOrNull() function to safely retrieve the largest element from a list of integers, handling the case when the list might be empty.
Code
fun main() {
val numbers = listOf(3, 7, 2, 9, 4)
// Find the maximum value in the list; returns null if the list is empty
val maxValue = numbers.maxOrNull()
if (maxValue != null) {
println("The maximum value is $maxValue")
} else {
println("The list is empty, no maximum value found.")
}
}
Key Points
- Kotlin's
maxOrNull()function returns the largest element or null if the list is empty. - Always handle the null case to avoid runtime exceptions when working with potentially empty lists.
- Using Kotlin's standard library functions simplifies common tasks like finding maximum values.
- Lists in Kotlin are immutable by default; you can use
mutableListOfif you need to modify elements.