Search code examples
javastringjava-8concatenationoption-type

Concatenate two or more optional string in Java 8


I have a rather simple question for you guys. In Java 8 it was introduced the Optional type. I have two objects of type Optional<String> and I want to know which is the more elegant way to concatenate them.

Optional<String> first = Optional.ofNullable(/* Some string */);
Optional<String> second = Optional.ofNullable(/* Some other string */);
Optional<String> result = /* Some fancy function that concats first and second */;

In detail, if one of the two original Optional<String> objects was equal to Optional.empty(), I want the whole concatenation to be empty too.

Please, note that I am not asking how to concatenate the evaluation of two Optionals in Java, but how to concatenate two Strings that are inside some Optional.

Thanks in advance.


Solution

  • 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.