Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the max element from an array list of objects?

Collections.max(arraylist) doesn't work, and a regular for loop won't work either.

What I have is:

ArrayList<Forecast> forecasts = current.getForecasts();

Collections.max(forecast) gives me this error:

The method max(Collection<? extends T>) in the type Collections is
not applicable for the arguments (ArrayList<Forecast>)

The ArrayList holds Forecast objects which each has an int field for the temperature of each day. I am trying to store the max in an int max.

like image 848
Josh Cuevas Avatar asked Apr 29 '17 23:04

Josh Cuevas


People also ask

How do you find the maximum element 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 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.


1 Answers

As your ArrayList contains Forecast objects you'll need to define how the max method should find the maximum element within your ArrayList.

something along the lines of this should work:

ArrayList<Forecast> forecasts = new ArrayList<>();
// Forecast object which has highest temperature
Forecast element = Collections.max(forecasts, Comparator.comparingInt(Forecast::getTemperature));
// retrieve the maximum temperature
int maxTemperature = element.getTemperature();
like image 155
Ousmane D. Avatar answered Oct 21 '22 05:10

Ousmane D.