There is an ArrayList which stores integer values. I need to find the maximum value in this list. E.g. suppose the arrayList stored values are : 10, 20, 30, 40, 50
and the max
value would be 50
.
What is the efficient way to find the maximum value?
@Edit : I just found one solution for which I am not very sure
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(100); /* add(200), add(250) add(350) add(150) add(450)*/
Integer i = Collections.max(arrayList)
and this returns the highest value.
Another way to compare the each value e.g. selection sort or binary sort algorithm
Then the length of the ArrayList can be found by using the size() function. After that, the first element of the ArrayList will be store in the variable min and max. Then the for loop is used to iterate through the ArrayList elements one by one in order to find the minimum and maximum from the array list.
In order to compute minimum element of ArrayList with Java Collections, we use the Collections. min() method.
You can use Collections. max as suggested by Steve Kuo, or in Java 8, use Arrays. stream to convert the array into a stream, then call Stream. max .
You can use the Collections API
to achieve what you want easily - read efficiently - enough
Javadoc for Collections.max
Collections.max(arrayList);
Returns the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface.
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