Concatenate two or more optional string in Java 8

The solution I found is the following:

first.flatMap(s -> second.map(s1 -> s + s1));

which can be cleaned using a dedicated method, such the following:

first.flatMap(this::concat);
Optional<String> concat(String s) {
    second.map(s1 -> s + s1);
}

However, I think that something better can be found.

If we want to generalize to a list or an array of Optional<String>, then we can use something similar to the following.

Optional<String> result =
    Stream.of(Optional.of("value1"), Optional.<String>empty())
          .reduce(Optional.of(""), this::concat);

// Where the following method id used
Optional<String> concat(Optional<String> first, Optional<String> second) {
    return first.flatMap(s -> second.map(s1 -> s + s1));
}

Note that in order to compile the above code, we have to manually bind the type variable of Optional.empty() to String.


You can stream the Optionals and reduce them with a concat.

Optional<String> first = Optional.of("foo");
Optional<String> second = Optional.of("bar");
Optional<String> result = Stream.of(first, second).flatMap(Optional::stream).reduce(String::concat);

If you are using Java 8 replace the flatMap operator with filter(Optional::isPresent).map(Optional::get).

Consider also to use the joining collectors: this will return String, not an Optional<String>.