Sling Academy
Home/Kotlin/Finding the Minimum and Maximum in a Collection in Kotlin

Finding the Minimum and Maximum in a Collection in Kotlin

Last updated: December 05, 2024

In Kotlin, finding the minimum and maximum values in a collection is made simple with its powerful standard library functions. Understanding how to leverage these functions can save you time and improve the efficiency of your code. In this article, we'll explore various ways to determine the smallest and largest elements in a list and other collection types in Kotlin.

Using the minOrNull and maxOrNull Functions

The Kotlin standard library provides useful extension functions minOrNull() and maxOrNull() to easily find the minimum and maximum values of a collection. These functions return a nullable type, as there's a possibility that the collection could be empty.

Here's a basic example using a list of integers:

val numbers = listOf(5, 3, 8, 1, 9)

val minValue = numbers.minOrNull()
val maxValue = numbers.maxOrNull()

println("Minimum value: $minValue") // Output: Minimum value: 1
println("Maximum value: $maxValue") // Output: Maximum value: 9

Handling Empty Collections

Since minOrNull() and maxOrNull() return null for empty collections, you must handle these cases in your code:

val emptyList = emptyList<Int>()

val minEmptyValue = emptyList.minOrNull() ?: "No minimum value in an empty list"
val maxEmptyValue = emptyList.maxOrNull() ?: "No maximum value in an empty list"

println(minEmptyValue) // Output: No minimum value in an empty list
println(maxEmptyValue) // Output: No maximum value in an empty list

Using minOf and maxOf for Non-nullable Results

When working with non-empty collections, you can use minOf and maxOf, which return non-null values directly. These methods throw an exception if the collection is empty, so they're safer to use with verified non-empty collections.

val numbers = listOf(7, 2, 10, 4, 6)

val minValue = numbers.minOf { it }
val maxValue = numbers.maxOf { it }

println("Min value: $minValue") // Output: Min value: 2
println("Max value: $maxValue") // Output: Max value: 10

Finding Min and Max with Specific Condition

You might need to find the minimum or maximum value based on certain conditions, like the absolute value of the numbers. minByOrNull and maxByOrNull are helpful in such cases, allowing you to specify a condition:

val numbers = listOf(-4, -2, 3, 7, -9)

val minByAbs = numbers.minByOrNull { Math.abs(it) }
val maxByAbs = numbers.maxByOrNull { Math.abs(it) }

println("Number with min absolute value: $minByAbs") // Output: Number with min absolute value: -2
println("Number with max absolute value: $maxByAbs") // Output: Number with max absolute value: -9

Conclusion

Kotlin makes finding the minimum and maximum in a collection straightforward with its range of functions for different scenarios. Choosing between nullable and non-nullable methods depends on whether your collection might be empty. With functions like minOf, maxOf, minByOrNull, and maxByOrNull, you can efficiently tailor your approach based on the specific needs of your application.

Next Article: Counting Elements That Meet a Specific Condition in Kotlin

Previous Article: Using `reduce` and `fold` for Custom Aggregations in Kotlin

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin