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

Josh Cuevas :

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.

Ousmane D. :

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();

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=475696&siteId=1