Java streams: Optional to stream

Jordi :

This is my code:

Optional<Application> application = this.applicationDao.findById(id);

where, Application class is:

public class Application {
    private String code;    
    private Collection<ApplicationQuote> quotes;
}

I need to create an stream from return Optional<Application> like this:

(app, quote-1) > (app, quote-2) > ... > (app, quote-n)

Where each quote-n is inside returned Optional<Application>.quotes.

I hope I've explained so well.

Up to now, I've been able to write this code, but I don't feel confortable with that:

Optional<Application> application = this.applicationDao.findById(id);
    application.map(app -> Pair.of(app, Optional.ofNullable(app.getQuotes())))
        .filter(quote -> quote.getValue().isPresent())
        .map(quote -> quote.getValue().get().stream().map(q -> Pair.of(quote.getKey(), q)));
Naman :

Optional.orElse

Ideally what you currently have is Optional<Stream<Pair<Application, ApplicationQuote>>> optionalPairStream and what you might just be looking for just add a default case and get just the Stream as :

Stream<Pair<Application, ApplicationQuote>> pairStream = application
        .map(app -> Pair.of(app, Optional.ofNullable(app.getQuotes())))
        .filter(quote -> quote.getValue().isPresent())
        .map(quote -> quote.getValue().get().stream().map(q -> Pair.of(quote.getKey(), q)))
        .orElse(Stream.empty());

Optional.stream

With Java9, you can update the same code as:

Stream<Pair<Application, ApplicationQuote>> pairStream = application
           .map(app -> Pair.of(app, Optional.ofNullable(app.getQuotes())))
           .filter(quote -> quote.getValue().isPresent())
           .stream() // new API
           .flatMap(quote -> quote.getValue().orElse(Collections.emptyList())
                   .stream().map(q -> Pair.of(quote.getKey(), q)));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=93761&siteId=1