Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join strings with a separator and stripping empty ones

Tags:

java

string

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:

  • Scenario #1 Actual output should be "A / B / C"
  • Scenario #2 When s1 is empty, output should be "B / C"
  • Scenario #3 When s2 is empty, output should be "A / C"
  • Scenario #4 When s3 is empty, output should be "A / B"`

Is this possible using ternary operation?

like image 388
IMJS Avatar asked May 14 '12 08:05

IMJS


3 Answers

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.

like image 126
jhunovis Avatar answered Nov 15 '22 22:11

jhunovis


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(" - "));
like image 25
7dev70 Avatar answered Nov 16 '22 00:11

7dev70


You can do:

result = ((s1==null)?"":(s1+"/"))+((s2==null)?"":(s2+"/"))+((s3==null)?"":s3);

See it

like image 34
codaddict Avatar answered Nov 16 '22 00:11

codaddict