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

前端 未结 6 1692
甜味超标
甜味超标 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:40

    A straightforward approach using any mutable Pair class:

    final Pair pair = new Pair<>();
    final Comparator comparator = ...;
    Stream.of(...).forEachOrdered(e -> {
        if(pair.first == null || comparator.compare(e, pair.first) < 0){
            pair.first = e;
        }
        if(pair.second == null || comparator.compare(e, pair.second) > 0){
            pair.second = e;
        }
    });
    

提交回复
热议问题