Skip to content
DeveloperMemos

Using min and max in Kotlin

Kotlin, Android Development1 min read

When working with collections or arrays in Kotlin, it is often necessary to find the smallest or largest value among the elements. Kotlin provides convenient functions called min() and max() that allow you to easily determine the minimum and maximum values in a collection. In this article, we will explore how to use these functions with examples in Kotlin, focusing on Android development scenarios.

Finding the Minimum Value

To find the minimum value in a collection or array, you can use the min() function provided by Kotlin. The min() function returns the smallest element based on the natural order defined for the elements.

Here's an example of finding the minimum value in a list of integers:

1val numbers = listOf(5, 10, 2, 8, 3)
2val minNumber = numbers.min()
3println("Minimum number: $minNumber")

The above code will output:

1Minimum number: 2

In this case, the min() function returns the smallest element in the list, which is 2.

Finding the Maximum Value

Similar to finding the minimum value, Kotlin also provides the max() function to find the maximum value in a collection or array. The max() function returns the largest element based on the natural order defined for the elements.

Let's see an example of finding the maximum value in an array of doubles:

1val temperatures = doubleArrayOf(25.5, 30.0, 28.3, 32.1)
2val maxTemperature = temperatures.max()
3println("Maximum temperature: $maxTemperature")

The output will be:

1Maximum temperature: 32.1

In this example, the max() function returns the largest element in the array, which is 32.1.

Customizing Order

By default, the min() and max() functions use the natural order of the elements to determine the minimum and maximum values. However, you can also provide a custom comparator if you need to define a different ordering.

Let's say we have a list of strings representing names, and we want to find the name that comes last alphabetically. We can achieve this by using a custom comparator with the min() function:

1val names = listOf("John", "Alice", "Bob", "Zoe")
2val lastName = names.minWith(compareByDescending { it })
3println("Last name: $lastName")

The output will be:

1Last name: Zoe

In this case, the minWith() function is used with a custom comparator that compares the names in descending order. As a result, "Zoe" is determined as the last name alphabetically.

Conclusion

In this article, we explored how to use the min() and max() functions in Kotlin to find the minimum and maximum values in a collection or array. We saw examples of finding the minimum and maximum values, as well as customizing the ordering using a custom comparator when needed. These functions are handy tools when working with collections and can simplify tasks that involve searching for extreme values.