2

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 null again.
How could I avoid null (and filter(Objects::nonNull)) using Optional consistently?

1
  • 3
    Java 9: flatMap(site -> Site.parseStub(site).stream()).collect(toList()) Commented Dec 9, 2015 at 9:41

1 Answer 1

7

Here's one way:

return sites.stream()
        .map(Site::parseStub)
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.