27

I saw this answer of how to join String[] to comma separated string.

However I need the util to join the string in the array only if the values are not empty.

What is the best way to do it? without looping before on the String[] to remove. I prefer one method that does both.

EDITED

for instance:

I, love, , u

will be:

 I love u
Community
  • 1
  • 1
Dejell
  • 13,947
  • 40
  • 146
  • 229

9 Answers9

52

In Java 8 you can use Stream:

    List<String> list = Arrays.asList("I", " ", "love", null, "you");
    String message = list.stream().filter(StringUtils::isNotBlank)
                     .collect(Collectors.joining(", "));
    System.out.println("message = " + message);
Sprinter
  • 717
  • 5
  • 11
9

For Java 8 here is a solution using stream API .Filter null and empty Strings and join with a space between each string

String joined = Stream.of(I, love, , u)
      .filter(s -> s != null && !s.isEmpty())
      .collect(Collectors.joining(" "));
Mero
  • 622
  • 12
  • 24
  • 2
    While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find [how to write a good answer](https://stackoverflow.com/help/how-to-answer) very helpful. Please [edit] your answer - [From Review](https://stackoverflow.com/review/low-quality-posts/21998868) – Nick Jan 23 '19 at 01:31
  • 1
    Nobody cares about explaining words when [Brian Goetz makes the same answer](https://stackoverflow.com/a/36706013/2104560) –  Oct 15 '19 at 09:26
5

For only null skip guava the best choice:

Joiner.on(" ").skipNulls().join("I", null, "love", null, "u")
Grigory Kislin
  • 16,647
  • 10
  • 125
  • 197
5

A pure Java 11 solution is:

String message = Stream.of("I", null, "Love", "     ", "You")
                       .filter(Objects::nonNull)
                       .filter(Predicate.not(String::isBlank))
                       .collect(Collectors.joining(" "));
System.out.println(message);

I Love You

If you really need to use array - then instead Stream.of() you can do:

Arrays.stream(new String[] { "I", null, "Love", "     ", "You" })
nyxz
  • 6,918
  • 9
  • 54
  • 67
3

Any problem with checking for null/empty?

String[] values = ?;
if (values != null && values.length > 0) {
  // join
}

The answer you pointed to already does the join using StringUtils.join

Your requirement doesn't quite fit with that, but it is so simple that it seems best to implement your own join loop, e.g.

    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (String word: words) {
        if (word != null && (word = word.trim()).length() > 0) {
            if (first) {
                first = false;
            } else {
                sb.append(',');
            }
            sb.append(word);
        }
    }
ewan.chalmers
  • 16,145
  • 43
  • 60
2

Why doesn't simply loop on array and use StringBuilder to build comma separated string for not null values only.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
1

Without any API or library, we could join non-blank, not-null string array as follows:

User-defined method:

public String joinNonBlankStringArray(String s[], String separator) {
    StringBuilder sb = new StringBuilder();
    if (s != null && s.length > 0) {
        for (String w : s) {
            if (w != null && !w.trim().isEmpty()) {
                sb.append(w);
                sb.append(separator);
            }
        }
    }
    return sb.substring(0, sb.length() - 1);// length() - 1 to cut-down last extra separator
}

Calling user-defined method:

String s[] = {" ","abc", "", "XYZ", "      ", null, "123", null};
String joinVal = joinNonBlankStringArray(s, ",");// "abc,XYZ,123"
mmuzahid
  • 2,252
  • 23
  • 42
1
public class So20111214a {
    public static String join(String[] argStrings) {
        if (argStrings == null) {
            return "";
        }
        String ret = "";
        if (argStrings.length > 0) {
            ret = argStrings[0];
        } // if
        for (int i = 1; i<argStrings.length; i++) {
            ret += (argStrings[i] == null) 
                    ? "" 
                    : (argStrings[i].isEmpty() 
                        ? "" 
                        :  ( "," + argStrings[i] ) );
        } // for
        return ret;
    } // join() method

    public static void main(String[] args) {
        String[] grandmasters = {  
            "Emanuel Lasker", 
            "José Raúl Capablanca", 
            "Alexander Alekhine", 
            "Siegbert Tarrasch", 
            "Frank Marshall"  
        };
        String[] s1 = null;
        String[] s2 = {};
        String[] s3 = { "Mikhail Botvinnik" };
        System.out.println(join(s1));
        System.out.println(join(s2));
        System.out.println(join(s3));
        System.out.println(join(grandmasters));
        System.out.println(join(new String[]{"I", "love", "", null, "u!"}));
    } // main() method

    /* output:
    <empty string>
    <empty string>
    Mikhail Botvinnik
    Emanuel Lasker,José Raúl Capablanca,Alexander Alekhine,Siegbert Tarrasch,Frank Marshall
    I,love,u!
    */

} // So20111214a class

PS: Sorry for using the ? operator - I had to do it quickly, I am at work. :)

DejanLekic
  • 18,787
  • 4
  • 46
  • 77
  • 1
    This works well as long as the first element of the array is not null or empty. However, it would be easy enough to loop through elements to determine the first non-null/empty element and set the initial index of the second loop based on that index. – Larry Hector Dec 03 '18 at 22:27
-3

Jakarta StringUtils does it. Here is the code from there:

public static String join(Object[] array, String separator) {
    if (array == null) {
        return null;
    }
    return join(array, separator, 0, array.length);
}
AlexR
  • 114,158
  • 16
  • 130
  • 208