Concise way to get both min and max value of Java 8 stream

前端 未结 6 1696
甜味超标
甜味超标 2020-12-15 03:53

Is there a concise way to extract both the min and max value of a stream (based on some comparator) in one pass?

There appear to be many ways to get the min and max

6条回答
  •  生来不讨喜
    2020-12-15 04:27

    The summarizingInt collector works well if you have a Stream of Integers.

    IntSummaryStatistics stats = Stream.of(2,4,3,2)
          .collect(Collectors.summarizingInt(Integer::intValue));
    
    int min = stats.getMin();
    int max = stats.getMax();
    

    If you have doubles you can use the summarizingDouble collector.

    DoubleSummaryStatistics stats2 = Stream.of(2.4, 4.3, 3.3, 2.5)
      .collect(Collectors.summarizingDouble((Double::doubleValue)));
    

提交回复
热议问题