Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate string values with delimiter handling null and empty strings? [duplicate]

In Java 8 I have some number of String values and I want to end up with a comma delimited list of valid values. If a String is null or empty I want to ignore it. I know this seems common and is a lot like this old question; however, that discussion does not address nulls AND spaces (I also don't like the accepted answer).

I've looked at Java 8 StringJoiner, Commons StringUtils (join) and trusty Guava (Joiner) but none seems like a full solution. The vision:

 where: val1 = "a", val2 = null, val3 = "", val4 = "b"    String niceString = StringJoiner.use(",").ignoreBlanks().ignoreNulls()     .add(val1).add(val2).add(val3).add(val4).toString(); 

...would result in niceString = a,b

Isn't there a nice way to do this (that doesn't involve for loops, loading strings into a list, and/or regex replaces to remove bad entries)?

like image 815
eze Avatar asked Apr 18 '16 23:04

eze


People also ask

Can you concatenate a string with null?

Using the String.concat() method is a good choice when we want to concatenate String objects. The empty String returned by the getNonNullString() method gets concatenated to the result, thus ignoring the null objects.

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

When SET CONCAT_NULL_YIELDS_NULL is ON, concatenating a null value with a string yields a NULL result. For example, SELECT 'abc' + NULL yields NULL . When SET CONCAT_NULL_YIELDS_NULL is OFF, concatenating a null value with a string yields the string itself (the null value is treated as an empty string).

How do I concatenate an empty string in Java?

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

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.


1 Answers

String joined =      Stream.of(val1, val2, val3, val4)           .filter(s -> s != null && !s.isEmpty())           .collect(Collectors.joining(",")); 
like image 98
Brian Goetz Avatar answered Sep 24 '22 10:09

Brian Goetz