spinlok :
I have two Optional
strings, name1
and name2
. I want to join the two such that the result is also an Optional with:
- If either one is non-empty, the result should be the non-empty name.
- If both are non-empty, I want the result to be joined with the delimiter
AND
. - If both are empty, the result should be an empty
Optional
My attempt at this:
StringBuilder sb = new StringBuilder();
name1.ifPresent(sb::append);
name2.ifPresent(s -> {
if (sb.length() > 0) {
sb.append(" AND ");
}
sb.append(s);
}
Optional<String> joinedOpt = Optional.ofNullable(Strings.emptyToNull(sb.toString()));
This works, but seems ugly and not very functional.
PS: There is a similar question but the accepted answer is wrong. Specifically, if name1
is empty and name2
is not, it returns an empty optional.
shmosel :
One solution is to stream and reduce()
:
Optional<String> joinedOpt = Stream.of(name1, name2)
.filter(Optional::isPresent)
.map(Optional::get)
.reduce((a, b) -> a + " AND " + b);
Feel free to replace the filter/map combo with Java 9 or Guava as others have suggested.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=433473&siteId=1