I need the code logic for the following:
These are the three String variables,
String s1 = "A"; String s2 = "B"; String s3 = "C";
I need to have the following outputs based on the given scenarios:
Is this possible using ternary operation?
You can do it with with the help of Guava class Joiner and Apache Commons Lang StringUtils.defaultIfBlank:
Joiner.on("/").skipNulls().join(
defaultIfBlank(s1, null),
defaultIfBlank(s2, null),
defaultIfBlank(s3, null)
);
You can extract the three lines of "defaultIfBlank" into a method with a loop if you need to process an arbitrary number of strings.
A java8-way with a stream
Arrays.stream(new String[]{null, "", "word1", "", "word2", null, "word3", "", null})
.filter(x -> x != null && x.length() > 0)
.collect(Collectors.joining(" - "));
You can do:
result = ((s1==null)?"":(s1+"/"))+((s2==null)?"":(s2+"/"))+((s3==null)?"":s3);
See it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With