I have the following piece of code:
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 to simplify the above by means of the functional programming? I would like to use something similar to Stream.of(firstString, secondString).collect(joining(""))
.
CodePudding user response:
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"
CodePudding user response:
This...actually isn't too bad. The best you can do is
Stream.of(firstString, secondString)
.filter(StringUtils::isNotBlank)
.collect(joining("<br>"));
which you may or may not find simpler.