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.
In order to compute maximum element of ArrayList with Java Collections, we use the Collections. max() method.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With