Is it possible to filter out empty Optionals and map over the present ones in a single line with Java streams?

Viewed 107

I often find myself writing code like this:

return collectionOfOptionals.stream()
    .filter(Optional::isPresent)
    .map(Optional::get)
    .collect(toList());

But is there a way to compress those middle two lines into a single operation?

I can do this, but it feels even less satisfactory:

return collectionOfOptionals.stream()
    .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
    .collect(toList());
1 Answers
Related