I have this ArrayList
var amplititudes: ArrayList<Int> = ArrayList() amplititudes.add(1) amplititudes.add(2) amplititudes.add(3) amplititudes.add(4) amplititudes.add(3) amplititudes.add(2) amplititudes.add(1)
I want to get the maximum value i.e 4. What will be the easiest way to find the max element? I know about the max()
method , but it will forces me to use ?
with the return value since it could be null
. Is there any solution which is better than this?
In order to compute maximum element of ArrayList with Java Collections, we use the Collections. max() method.
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. Using minWith() & maxWith() function. The recommended solution is to find the minimum value in the list of objects is with the minWith() function that accepts a Comparator to compare objects based on a field value. Similarly, to find the maximum value in the list, you can use the maxWith() function.
You can use built-in functionality with maxOrNull
(docs):
val amplitudes = listOf(1,2,3,4,3,2,1) val max = amplitudes.maxOrNull() ?: 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With