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()
方法是
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)
当心NoSuchElementException这Optional#get可能抛出。
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |