Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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  

like image 918
user1010399 Avatar asked Oct 15 '22 23:10

user1010399


People also ask

How do you find the max and min of an ArrayList in Java?

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.

How do you find the minimum value in an ArrayList?

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

How do you find the maximum value of an array of objects in Java?

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 .


1 Answers

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.

like image 330
gotomanners Avatar answered Oct 17 '22 13:10

gotomanners