20
\$\begingroup\$

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
            .stream()
            .filter(Optional::isPresent)
            .collect(Collectors.mapping(Optional::get, Collectors.toList()));
\$\endgroup\$
35
\$\begingroup\$

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

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

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(...).

| improve this answer | |
\$\endgroup\$
-1
\$\begingroup\$

If you are using rxJava you can do something like:

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

Flux<String> strings = maybeStrings.handle((maybeString, synchronousSink) -> 
    maybeString.ifPresent(synchronousSink::next));
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Hi, on CodeReview it's expected to explain why your solution offers a better alternative than the current code :) \$\endgroup\$ – IEatBagels Nov 27 '18 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\$ – Doctor Parameter Nov 28 '18 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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