How do i write this in java8 in 1 line?
if (Optional.ofNullable(mapOfIntAndListOfObjects.get(spn)).isPresent()) {
Date paydate = Optional.ofNullable(mapOfIntAndListOfObjects.get(spn).stream().findFirst()).get().orElse(new MyObject()).getPayDate();
logger.info("paydate {} ", paydate);
return paydate;
}
return null;
Something like
Date payDate = mapOfIntAndListOfObjects.getOrDefault(spn, Collections.emptyList())
.stream()
.findFirst()
.orElse(new MyObject())
.getPayDate();
logger.info("paydate {} ", paydate);
return payDate;
You don't really seem to be in need of wrapping them around Optional
.
Try this:
return Optional.ofNullable(mapOfIntAndListOfObjects.getOrDefault(spn))
.map(List::stream)
.map(Stream::findFirst)
.map(MyObject::getPayDate)
.orElse(null); // or whatever default to return in case nothing found
Entirely uses the Optional
functionality as intended. ie no default lists/values needed anywhere (except for the choice of what to return when nothing found).
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.