How to find the max element from an array list of objects?

前端 未结 5 652
小鲜肉
小鲜肉 2021-01-18 13:55

Collections.max(arraylist) doesn\'t work, and a regular for loop won\'t work either.

What I have is:

ArrayList

        
5条回答
  •  北海茫月
    2021-01-18 14:39

    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 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();
    

提交回复
热议问题