如何从对象数组列表中找到max元素? [英] How to find the max element from an array list of objects?
本文介绍了如何从对象数组列表中找到max元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Collections.max(arraylist)
不起作用,常规的for
循环也不起作用.
Collections.max(arraylist)
doesn't work, and a regular for
loop won't work either.
我所拥有的是:
ArrayList<Forecast> forecasts = current.getForecasts();
Collections.max(forecast)
给我这个错误:
The method max(Collection<? extends T>) in the type Collections is
not applicable for the arguments (ArrayList<Forecast>)
ArrayList
容纳Forecast
个对象,每个对象都有一个用于每天温度的int
字段.我正在尝试将最大值存储在int max中.
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.
推荐答案
由于您的ArrayList
包含Forecast
对象,因此您需要定义max
方法应如何在ArrayList
中找到最大元素.
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();
这篇关于如何从对象数组列表中找到max元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文