How to find the maximum element from a list of arrays of objects?

Collections.max(arraylist)doesn't work, and the regular loop fordoesn't work either.

I have:

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

ArrayListcontains Forecastobjects, each of which has a field intfor the temperature of each day. I am trying to save max to int max.

+5
source share
5 answers

Since yours ArrayListcontains objects Forecast, you need to determine how the method maxshould find the maximum element in yours ArrayList.

something in accordance with 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();
+13
source

Another solution is to use a Reduce card:

Optional<Forecast> element = forecasts
                     .stream()
                     .reduce((a,b) -> a.getTemperature() > b.getTemperature() ? a : b );

That way you can even use use parallelStream()

+1

.

Forecast highest = forecasts.stream()
                            .max((fc1, fc2) -> fc1.getTemp() - fc2.getTemp())
                            .get();
+1

, arraylist

GetMaxValue ( ArrayList)

{

 ArrayList sortArrayList= arrayList;

 sortArrayList.Sort();

 sortArrayList.Reverse();

 return sortArrayList[0];

}

0

. , forecast , forecasts. , forecast. , , , Integer. Integer i = Integer.parseInt(forecasts); Collections.max(i)

-2

Source: https://habr.com/ru/post/1676007/


All Articles