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()
?
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.