Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 to simplify the above by means of the functional programming? I would like to use something similar to Stream.of(firstString, secondString).collect(joining("")).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading