I want to convert my list of optional strings to a list of strings by getting rid of the empty Optionals.

Is there a shorter version for achieving this than the following code (except statically importing the methods of Collectors)?

List<Optional<String>> stringsMaybe = Arrays.asList(Optional.of("Hi"),
                                      Optional.empty(), Optional.of(" there!"));

List<String> strings = stringsMaybe
            .collect(Collectors.mapping(Optional::get, Collectors.toList()));

2 Answers 2


It's more idiomatic to use .map on the stream instead of Collectors.mapping:


Without introducing a helper method or a custom collector, that's the shortest and clearest way to do this.

Since Java 9, Optional offers a stream method, enabling you to do .flatMap(Optional::stream) instead of .filter(...).map(...).


If you are using rxJava you can do something like:

Flux<Optional<String>> maybeStrings = Flux.just(
    Optional.of(" there!"));

Flux<String> strings = maybeStrings.handle((maybeString, synchronousSink) -> 
  • 1
    \$\begingroup\$ Hi, on CodeReview it's expected to explain why your solution offers a better alternative than the current code :) \$\endgroup\$
    – IEatBagels
    Nov 27, 2018 at 21:12
  • \$\begingroup\$ The only reason you'd want to use my example instead of the selected answer is if you're operating on a rxJava Flux rather than a Java 8 Stream. Technically this does not answer the question but someone searching for this example may benefit from this snippet none the less. \$\endgroup\$ Nov 28, 2018 at 19:54

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.