Skip to content
Advertisement

Rewrite nested ternary operators in functional way

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 simplify the above by means of the functional programming?

I would like to use something similar to

Stream.of(firstString, secondString).collect(joining(""))

Advertisement

Answer

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"

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement