I apologize in advance if this question has been asked, but I have been struggling to figure this out for a few hours now (googling everything I can) and really hope someone could help.
I am trying to collect two String values, which I am trying to get from a source, in to a single String, and return null
if these values do not exist (source.getA
returns null
).
So far, I have come up with this code:
if (source.getA() != null && source.getB() != null) {
target.setAAndB(Stream.of(source.getA(), source.getB())
.map(String::valueOf)
.collect(Collectors.joining(" ")));
} else {
target.setAandB(null);
}
How do I turn this in to a nice looking chain? I know there is a way, but I feel like I am missing a trick here.
EDIT:
target.setAandB(
Optional.of(
Stream.of(source.getA(), source.getB())
.map(String::valueOf)
.collect(Collectors.joining(" "))
).orElse(null)
);
Made a bit of progress, but here the orElse
will not work, because the collector still returns a string with two null
strings combined.
EDIT 2:
Thank you all for your answers, I found them very valuable and some valuable things to consider.