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
To concatenate null to a string, use the + operator.
isEmpty(< string >)Returns true if the string is null or empty.
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.
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.
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);
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(" "));
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