如何从对象数组列表中找到最大元素? [英] How to find the max element from an array list of objects?
本文介绍了如何从对象数组列表中找到最大元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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();
这篇关于如何从对象数组列表中找到最大元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文