Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join comma if not empty or null

Tags:

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 
like image 620
Dejell Avatar asked Dec 14 '11 09:12

Dejell


People also ask

Can you concatenate a null string?

To concatenate null to a string, use the + operator.

Does isEmpty work on null?

isEmpty(< string >)​Returns true if the string is null or empty.

Can we concatenate string and null in Java?

Let's say we want to concatenate the elements of a String array where any of the elements may be null. But, we may not want to display or append such “null” values to the output. We cannot avoid null elements from being concatenated while using the String.

How do you concatenate null values in a string in python?

To join multiple strings with possibly None values: Use the join() method with an optional delimiter. Use the filter() function to filter out any None values. The join() method returns a string which is the concatenation of the strings in the iterable.


2 Answers

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); 
like image 157
Sprinter Avatar answered Oct 23 '22 01:10

Sprinter


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(" ")); 
like image 34
Mero Avatar answered Oct 23 '22 03:10

Mero