如何从数组对象列表中找到max元素?

Jos*_*vas 5 java arrays arraylist

Collections.max(arraylist)不起作用,常规for循环也不起作用.

我有的是:

ArrayList<Forecast> forecasts = current.getForecasts();
Run Code Online (Sandbox Code Playgroud)

Collections.max(forecast) 给我这个错误:

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

ArrayList保持Forecast每个具有对象int字段的每一天的温度.我试图将max存储在int max中.

Ous*_* D. 13

作为ArrayList包含Forecast对象,您需要定义max方法应如何在您的内容中找到最大元素ArrayList.

这应该是有用的:

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();
Run Code Online (Sandbox Code Playgroud)