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

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

    Map each element of the stream to a pair, where the two elements represent the min and the max; and then reduce the pairs by taking the min of the mins, and the max of the maxes.

    For example, using some Pair class and some Comparator:

    Comparator comparator = ...;
    Optional> minMax = list.stream()
        .map(i -> Pair.of(i /* "min" */, i /* "max" */))
        .reduce((a, b) -> Pair.of(
            // The min of the min elements.
            comparator.compare(a.first, b.first) < 0 ? a.first : b.first,
            // The max of the max elements.
            comparator.compare(a.second, b.second) > 0 ? a.second : b.second));
    

提交回复
热议问题