Reputation: 3612
I need to define max minutes from set my code
carWashBoxSet.
stream().
filter(p -> p.getOrderTime() != null).
map(t -> t.getOrderTime()).
max(Date::compareTo).
get().
getMinutes();
The problem is if carWashBoxSet empty i get null pointer exeption, is it any to use smth like stream.ifNonEpty().Orelse()
?
Upvotes: 0
Views: 1735
Reputation: 4754
well i highly recommend to not use .get()
without .isPresent()
, because when the optional is empty, you will create a NoSuchElementException.
To bypass this i would map the getMinutes()
at the end, and add an .orElse()
or .orElseGet()
depending on what you expect as an alternative.
carWashBoxSet.stream()
.filter(p -> p.getOrderTime() != null)
.map(t -> t.getOrderTime())
.max(Date::compareTo)
.map(boxSet -> boxSet.getMinutes())
.orElse(/*another value*/);
if you do not expect an alternative and want to just process this value somehow, without further usage .ifPresent()
can also be a good choice.
carWashBoxSet.stream()
.filter(p -> p.getOrderTime() != null)
.map(t -> t.getOrderTime())
.max(Date::compareTo)
.map(boxSet -> boxSet.getMinutes())
.ifPresent( minutes -> System.out.println(minutes));
Upvotes: 3