如何从对象数组列表中找到max元素? [英] How to find the max element from an array list of objects?

查看:140
本文介绍了如何从对象数组列表中找到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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆