Find minimum and maximum value in an Integer List in Kotlin
This article explores different ways to find the minimum and maximum values in a list of integers in Kotlin.
1. Using min() and max() function
The standard solution in Kotlin is to use the native min() and max() function, which returns the minimum element and the maximum element in the list, respectively, according to the natural ordering of its elements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
fun findMin(list: List<Int>): Int? { return list.min() } fun findMax(list: List<Int>): Int? { return list.max() } fun main() { val list = listOf(10, 4, 2, 7, 6, 9) val min = findMin(list) println(min) // 2 val max = findMax(list) println(max) // 10 } |
2. Using reduce() function
We can also perform a reduction operation on the list’s values using the reduce() function, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun findMin(list: List<Int>): Int? { return list.reduce { a: Int, b: Int -> a.coerceAtMost(b) }; } fun findMax(list: List<Int>): Int? { return list.reduce { a: Int, b: Int -> a.coerceAtLeast(b) } } fun main() { val list = listOf(10, 4, 2, 7, 6, 9) val min = findMin(list) println(min) // 2 val max = findMax(list) println(max) // 10 } |
3. Using Sorting
If you sort the list in ascending order, then the first value in the sorted list would be the minimum value, and the last value would be the maximum. Note that this approach modifies the original array and is not preferred for large arrays.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
fun findMin(list: List<Int?>): Int? { return list.sortedWith(compareBy { it }).first() } fun findMax(list: List<Int?>): Int? { return list.sortedWith(compareBy { it }).last() } fun main() { val list = listOf(10, 4, 2, 7, 6, 9) val min = findMin(list) println(min) // 2 val max = findMax(list) println(max) // 10 } |
4. Custom Routine
Finally, you can also write your custom logic to find the minimum and maximum values in a list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
fun findMin(list: List<Int>): Int? { var min = Int.MAX_VALUE for (i in list) { min = min.coerceAtMost(i) } return min } fun findMax(list: List<Int>): Int? { var max = Int.MIN_VALUE for (i in list) { max = max.coerceAtLeast(i) } return max } fun main() { val list = listOf(10, 4, 2, 7, 6, 9) val min = findMin(list) println(min) // 2 val max = findMax(list) println(max) // 10 } |
That’s all about finding the minimum and maximum value in an Integer list 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 :)