【问题标题】:How to find the max element from an array list of objects?如何从对象数组列表中找到最大元素?
【发布时间】:2017-04-29 23:18:23
【问题描述】:

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 中。

【问题讨论】:

  • Forecast 类是否实现 Comparable?
  • Forecast 的 forecasts ArrayList 不是 int 数组。如果使用得当,循环和max() 都能正常工作。
  • 你必须使用 Compactor 接口
  • 不使用常规 for 循环如何工作?你能分享你试过的代码吗?
  • @PeterLawrey 你能详细说明一下吗?如果预测不是整数数组,我怎样才能得到其中的最大整数值?

标签: java arrays arraylist


【解决方案1】:

由于您的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();

【讨论】:

  • 完美运行!
【解决方案2】:

流非常适合解决这类问题。

Forecast highest = forecasts.stream()
                            .max((fc1, fc2) -> fc1.getTemp() - fc2.getTemp())
                            .get();

【讨论】:

    【解决方案3】:

    另一种解决方案是使用 map reduce:

    Optional<Forecast> element = forecasts
                         .stream()
                         .reduce((a,b) -> a.getTemperature() > b.getTemperature() ? a : b );
    

    这样你甚至可以使用parallelStream()

    【讨论】:

      【解决方案4】:

      这是从arraylist返回最大值的简单方法

      公共静态对象GetMaxValue(ArrayList arrayList)

      {

       ArrayList sortArrayList= arrayList;
      
       sortArrayList.Sort();
      
       sortArrayList.Reverse();
      
       return sortArrayList[0];
      

      }

      【讨论】:

        【解决方案5】:

        我有两个想法。首先,你在参数中使用了forecast,但应该是forecasts。此外,您从未提供过Forecast 类的代码。我可能错了,因为我没有看到您的所有代码,但是您需要将 Forecast 转换为 Integer。通过Integer i = Integer.parseInt(forecasts); 执行此操作,下次使用Collections.max(i)

        【讨论】:

        • 你只能解析一个String,parseInt返回一个int,而不是一个Integer,一旦你只有一个值,调用max()是没有意义的,因为它是最大值。
        猜你喜欢
        • 2019-08-31
        • 2021-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 2020-07-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多