Join comma if not empty or null
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" })
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(" "));
For only null skip guava the best choice:
Joiner.on(" ").skipNulls().join("I", null, "love", null, "u")
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);