如何将.min()或.max()作为流的方法参数?

Der*_*usA 3 java max min java-8 java-stream

如何在这样的代码中将.min()or .max()表达式作为方法参数传递:

给定代码:

private LocalDate getMaxDate() {
    LocalDate maxdate = dates.stream()
              .max( Comparator.comparing( LocalDate::toEpochDay ) )
              .get();
}

private LocalDate getMinDate() {
    LocalDate maxdate = dates.stream()
              .min( Comparator.comparing( LocalDate::toEpochDay ) )
              .get();
}
Run Code Online (Sandbox Code Playgroud)

我希望拥有的代码:

private LocalDate getDate(SomeType _EXPR_){
        LocalDate maxdate = dates.stream()
                  ._EXPR_( Comparator.comparing( LocalDate::toEpochDay ) )
                  .get();
    }
Run Code Online (Sandbox Code Playgroud)

提示:_EXPR_应为.min(),有时.max()

And*_*lko 5

方法是

private LocalDate getDate(Function<Comparator<LocalDate>, BinaryOperator<LocalDate>> f) {
  return dates.stream()
              .reduce(f.apply(Comparator.comparing(LocalDate::toEpochDay)))
              .get();
}
Run Code Online (Sandbox Code Playgroud)

调用它,使用

getDate(BinaryOperator::maxBy);
getDate(BinaryOperator::minBy);
Run Code Online (Sandbox Code Playgroud)

当心NoSuchElementExceptionOptional#get可能抛出。