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

后端 未结 8 909
无人及你
无人及你 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 00:51

    You may either convert the stream to IntStream:

    OptionalInt max = list.stream().mapToInt(Integer::intValue).max();
    

    Or specify the natural order comparator:

    Optional<Integer> max = list.stream().max(Comparator.naturalOrder());
    

    Or use reduce operation:

    Optional<Integer> max = list.stream().reduce(Integer::max);
    

    Or use collector:

    Optional<Integer> max = list.stream().collect(Collectors.maxBy(Comparator.naturalOrder()));
    

    Or use IntSummaryStatistics:

    int max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax();
    
    0 讨论(0)
  • 2020-12-23 00:53

    Another version could be:

    int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();
    
    0 讨论(0)
  • 2020-12-23 00:53

    With stream and reduce

    Optional<Integer> max = list.stream().reduce(Math::max);
    
    0 讨论(0)
  • 2020-12-23 00:54
    int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
    
    0 讨论(0)
  • 2020-12-23 00:58

    You could use int max= Stream.of(1,2,3,4,5).reduce(0,(a,b)->Math.max(a,b)); works for both positive and negative numbers

    0 讨论(0)
  • 2020-12-23 00:59
    int value = list.stream().max(Integer::compareTo).get();
    System.out.println("value  :"+value );
    
    0 讨论(0)
提交回复
热议问题