Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 562
riccardo.cardin Avatar asked Sep 28 '17 15:09

riccardo.cardin


1 Answers

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

like image 193
lmarx Avatar answered Sep 30 '22 10:09

lmarx