Find minimum and maximum elements in an array in Kotlin
This article explores different ways to find the minimum and maximum element in an array in Kotlin.
1. Using toList() function
The idea is to convert the array into a list and call the min() and max() functions of the List interface to get the minimum and maximum element.
|
1 2 3 4 5 6 7 |
fun main() { val arr = arrayOf(6, 3, 2, 5, 10) val ints = arr.toList() println("Minimum: ${ints.min()}") // Minimum: 2 println("Maximum: ${ints.max()}") // Maximum: 2 } |
2. Using map() function
Here, the idea is to get a list of valid indices for the array and transform the indices into the corresponding element in the array using the map() function. Then you can call the max() and min() function to get the minimum and maximum element, respectively.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val arr: Array<Int> = arrayOf(6, 3, 2, 5, 10) val max = arr.indices.map { i: Int -> arr[i] }.max() val min = arr.indices.map { i: Int -> arr[i] }.min() println("Minimum: $min") // Minimum: 2 println("Maximum: $max") // Maximum: 2 } |
3. Using Sorting
Another plausible way is to sort the array in ascending order. Then the minimum and maximum elements would be the first and last array elements, respectively. However, this approach modifies the original array and is not preferred for large arrays.
|
1 2 3 4 5 6 7 8 |
fun main() { val arr: Array<Int> = arrayOf(6, 3, 2, 5, 10) arr.sort(); println("Minimum: ${arr.first()}") // Minimum: 2 println("Maximum: ${arr.last()}") // Maximum: 10 } |
4. Using summaryStatistics() function
To get the minimum and maximum element, you can also call the min and max properties on a IntSummaryStatistics object, which provides summary data about the elements of a stream.
|
1 2 3 4 5 6 7 8 9 |
import java.util.Arrays fun main() { val arr: IntArray = intArrayOf(6, 3, 2, 5, 10) val stats = Arrays.stream(arr).summaryStatistics() println("Minimum: " + stats.min) // Minimum: 2 println("Maximum: " + stats.max) // Maximum: 10 } |
5. Custom Routine
Finally, you can also write your own routine for finding the minimum and maximum element in the array:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
fun getMax(A: Array<Int>): Int { var max = Int.MIN_VALUE for (i in A) { max = max.coerceAtLeast(i) } return max } fun getMin(A: Array<Int>): Int { var min = Int.MAX_VALUE for (i in A) { min = min.coerceAtMost(i) } return min } fun main() { val arr: Array<Int> = arrayOf(6, 3, 2, 5, 10) println("Minimum: " + getMin(arr)) // Minimum: 2 println("Maximum: " + getMax(arr)) // Maximum: 10 } |
That’s all about finding the minimum and maximum elements in an array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)