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

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

    For a pure Java solution that's fairly concise, you can use .peek(). This is not truly Functional, as anything that .peek() does is a side-effect. But this does do it all in one pass, doesn't require sorting and isn't too verbose. There is a "temp" Object, the AtomicRef, but you'll probably allocate a local var/ref to hold the min and max anyway.

    Comparator cmp = ...
    Stream source = ...
    final AtomicReference min = new AtomicReference();
    Optional max = source.peek(t -> {if (cmp.compare(t,min.get()) < 0) min.set(t);})
        .max(cmp);
    //Do whatever with min.get() and max.get()
    

提交回复
热议问题