How to Find Minimum Value in a List in Kotlin
In Kotlin, you can find the minimum value in a list using the
minOrNull() function, which returns the smallest element or null if the list is empty. For example, val minValue = list.minOrNull() gives you the minimum value safely.Syntax
The basic syntax to find the minimum value in a list is:
list.minOrNull(): Returns the smallest element ornullif the list is empty.
This function works on lists of comparable elements like numbers or strings.
kotlin
val list = listOf(5, 3, 8, 1, 4) val minValue = list.minOrNull()
Example
This example shows how to find the minimum value in a list of integers and handle the case when the list is empty.
kotlin
fun main() {
val numbers = listOf(10, 20, 5, 30)
val minNumber = numbers.minOrNull()
println("Minimum value: $minNumber")
val emptyList = listOf<Int>()
val minEmpty = emptyList.minOrNull()
println("Minimum value in empty list: $minEmpty")
}Output
Minimum value: 5
Minimum value in empty list: null
Common Pitfalls
One common mistake is using min() which is deprecated and can cause errors. Also, not handling null when the list is empty can cause crashes.
Always use minOrNull() and check for null if the list might be empty.
kotlin
fun main() {
val emptyList = listOf<Int>()
// Wrong: min() is deprecated and unsafe
// val minValue = emptyList.min() // This will cause error
// Right: use minOrNull() and check for null
val minValue = emptyList.minOrNull()
if (minValue != null) {
println("Minimum: $minValue")
} else {
println("List is empty, no minimum value.")
}
}Output
List is empty, no minimum value.
Quick Reference
| Function | Description |
|---|---|
| minOrNull() | Returns the smallest element or null if list is empty |
| min() | Deprecated, avoid using |
| maxOrNull() | Returns the largest element or null if list is empty |
Key Takeaways
Use
minOrNull() to safely find the minimum value in a Kotlin list.Always check for
null when the list might be empty to avoid errors.Avoid using deprecated
min() function.minOrNull() works on any list of comparable elements like numbers or strings.