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

前端 未结 5 654
小鲜肉
小鲜肉 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:31

    Streams are perfect for these sort of problems.

    Forecast highest = forecasts.stream()
                                .max((fc1, fc2) -> fc1.getTemp() - fc2.getTemp())
                                .get();
    
    0 讨论(0)
  • 2021-01-18 14:31

    Another solution is use map reduce:

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

    In this way you could even use use parallelStream()

    0 讨论(0)
  • 2021-01-18 14:38

    I have two ideas. First of all, you used forecast in the parameter, but it should be forecasts. Also, you never gave your code for the class Forecast. I may be wrong, because I didn't see all of your code, but you need to convert Forecast to a Integer. Do this by Integer i = Integer.parseInt(forecasts); Next use Collections.max(i)

    0 讨论(0)
  • 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<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();
    
    0 讨论(0)
  • 2021-01-18 14:40

    here is the simple method that return a max value from arraylist

    public static object GetMaxValue(ArrayList arrayList)

    {

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

    }

    0 讨论(0)
提交回复
热议问题