DerBenniAusA :
How can I pass the .min()
or .max()
expression as a method parameter in a code like this:
Given code:
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();
}
Code that I expect to have:
private LocalDate getDate(SomeType _EXPR_){
LocalDate maxdate = dates.stream()
._EXPR_( Comparator.comparing( LocalDate::toEpochDay ) )
.get();
}
Hint: _EXPR_
shall be .min()
, sometimes .max()
Andrew Tobilko :
The method is
private LocalDate getDate(Function<Comparator<LocalDate>, BinaryOperator<LocalDate>> f) {
return dates.stream()
.reduce(f.apply(Comparator.comparing(LocalDate::toEpochDay)))
.get();
}
To call it, use
getDate(BinaryOperator::maxBy);
getDate(BinaryOperator::minBy);
Beware of NoSuchElementException
which Optional#get
may throw.