Java equivalent of PHP’s implode(‘,’ , array_filter( array () ))

By | August 13, 2019


I often use this piece of code in PHP

$ordine['address'] = implode(', ', array_filter(array($cliente['cap'], $cliente['citta'] ,$cliente['provincia'])));

It clears empty strings and join them with a “,”. If only one remains it doesn’t add an extra unneeded comma. It doesn’t add a comma at the end. If none remains it returns empty string.

Thus I can get one of the following results

"Street abc 14"
"Street abc 14, 00168"
"Street abc 14, 00168, Rome"

What is the best Java implementation (less code) in Java without having to add external libraries (designing for Android) ?


Updated version using Java 8 (original at the end of post)

If you don’t need to filter any elements you can use

Since Java 8 we can use StringJoiner (instead of originally used StringBulder) and simplify our code.
Also to avoid recompiling " *" regex in each call of matches(" *") we can create separate Pattern which will hold its compiled version in some field and use it when needed.

private static final Pattern SPACES_OR_EMPTY = Pattern.compile(" *");
public static String implode(String separator, String... data) {
    StringJoiner sb = new StringJoiner(separator);
    for (String token : data) {
        if (!SPACES_OR_EMPTY.matcher(token).matches()) {
    return sb.toString();

With streams our code can look like.

private static final Predicate<String> IS_NOT_SPACES_ONLY = 

public static String implode(String delimiter, String... data) {

If we use streams we can filter elements which Predicate. In this case we want predicate to accept strings which are not only spaces – in other words string must contain non-whitespace character.

We can create such Predicate from Pattern. Predicate created this way will accept any strings which will contain substring which could be matched by regex (so if regex will look for "\S" predicate will accept strings like "foo ", " foo bar ", "whatever", but will not accept " " nor " ").

So we can use


or possibly little more descriptive, negation of strings which are only spaces, or empty


Next when filter will remove all empty, or containing only spaces Strings we can collect rest of elements. Thanks to Collectors.joining we can decide which delimiter to use.

Original answer (before Java 8)

public static String implode(String separator, String... data) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < data.length - 1; i++) {
    //data.length - 1 => to not add separator at the end
        if (!data[i].matches(" *")) {//empty string are ""; " "; "  "; and so on
    sb.append(data[data.length - 1].trim());
    return sb.toString();

You can use it like

System.out.println(implode(", ", "ab", " ", "abs"));


System.out.println(implode(", ", new String[] { "ab", " ", "abs" }));

Output ab, abs

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *