In Class Site, I have two utility methods.
The first one, parseStub, parses a Site into a Master if no errors occur; otherwise, it returns null. Using Optional:
public static Optional<Master> parseStub(Site site) {
// do some parse work; return Optional.empty() if the parse fails.
}
The second method parseStubs is to parse a list of Site into a list of Master. It reuses parseStub, and has to handle the possibly empty Optional<Master>:
public static List<Master> parseStubs(List<Site> sites) {
return sites.stream()
.<Master>map(site -> Site.parseStub(site).orElse(null))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
Note that in the code above, I introduced
nullagain.
How could I avoidnull(andfilter(Objects::nonNull)) usingOptionalconsistently?
flatMap(site -> Site.parseStub(site).stream()).collect(toList())