how to find maximum value from a Integer using stream in java 8?

后端 未结 8 910
无人及你
无人及你 2020-12-23 00:26

I have a list of Integer list and from the list.stream() I want the maximum value. What is the simplest way? Do I need comparator?

相关标签:
8条回答
  • 2020-12-23 01:00

    You can also use below code snipped:

    int max = list.stream().max(Comparator.comparing(Integer::valueOf)).get();
    

    Another alternative:

    list.sort(Comparator.reverseOrder()); // max value will come first
    int max = list.get(0);  
    
    0 讨论(0)
  • 2020-12-23 01:09

    Correct code:

    int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
    

    or

    int max = list.stream().reduce(Integer.MIN_VALUE, Integer::max);
    
    0 讨论(0)
提交回复
热议问题