Skip to content
Advertisement

How to get maximum value from the Collection (for example ArrayList)?

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  

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement