Collections.max(arraylist)不能工作,常规的for循环也不能工作。
我所拥有的是:
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中。
发布于 2017-04-30 07:30:12
由于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();发布于 2017-04-30 07:48:59
另一种解决方案是使用map reduce:
Optional<Forecast> element = forecasts
.stream()
.reduce((a,b) -> a.getTemperature() > b.getTemperature() ? a : b );通过这种方式,您甚至可以使用parallelStream()
发布于 2017-04-30 07:54:36
Streams是解决这类问题的最佳选择。
Forecast highest = forecasts.stream()
.max((fc1, fc2) -> fc1.getTemp() - fc2.getTemp())
.get();https://stackoverflow.com/questions/43701377
复制相似问题