Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Get Maximum value in ArrayList of Ints

Tags:

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?

like image 352
Dishonered Avatar asked May 29 '18 08:05

Dishonered


People also ask

How do you find the max value in an ArrayList?

In order to compute maximum element of ArrayList with Java Collections, we use the Collections. max() method.

How do you find the max value in Kotlin?

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.

How do you find the maximum value of a list of objects?

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.


1 Answers

You can use built-in functionality with maxOrNull (docs):

val amplitudes = listOf(1,2,3,4,3,2,1) val max = amplitudes.maxOrNull() ?: 0 
like image 71
s1m0nw1 Avatar answered Oct 03 '22 15:10

s1m0nw1