I have the following piece of code:
JavaScript
x
String firstString = "sth";
String secondString = "sthElse";
String stringsSpecialConcat = String.format("%s<br>%s", firstString, secondString);
boolean isFirstStringNotBlank = StringUtils.isNotBlank(firstString);
boolean isSecondStringNotBlank = StringUtils.isNotBlank(secondString);
return isFirstStringNotBlank ? (isSecondStringNotBlank ? stringsSpecialConcat : firstString) : (isSecondStringNotBlank ? secondString : "")
Could you please help me simplify the above by means of the functional programming?
I would like to use something similar to
JavaScript
Stream.of(firstString, secondString).collect(joining(""))
Advertisement
Answer
JavaScript
Stream.of(firstString, secondString)
.filter(StringUtils::isNotBlank)
.collect(Collectors.joining("<br>"))
Collectors.joining
will only insert a delimiter if there are 2 or more elements. In your case, that’s when both are non-empty.
If both are empty, the result is ""
If first is empty, the result is "second"
If second is empty, the result is "first"
If both are non-empty, the result is "first<br>second"