user1010399 user1010399 - 4 years ago 201
Java Question

how to get maximum value from the List/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 binaray sort algorithm

Answer Source

Sort the array in either ascending or descending order and pick either the first or last item in the array depending on the order!

Collections.sort(arrayList); // Sort the arraylist
arrayList.get(arrayList.size() - 1); //gets the last item, largest for an ascending sort

EDIT

On second thought, you can use the Collections API to achieve what you want easily - read efficiently - enough Javadoc for Collection.max

Collections.max(arrayList);

Returns the maximum element of the given collection, according to the specified comparator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download