Java equivalent of PHP's implode(',' , array_filter( array () ))

JavaPhp

Java Problem Overview


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)?

Java Solutions


Solution 1 - Java

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()) {
            sb.add(token);
        }
    }
    return sb.toString();
}   

With streams our code can look like.

private static final Predicate<String> IS_NOT_SPACES_ONLY = 
        Pattern.compile("^\\s*$").asPredicate().negate();

public static String implode(String delimiter, String... data) {
    return Arrays.stream(data)
            .filter(IS_NOT_SPACES_ONLY)
            .collect(Collectors.joining(delimiter));
}

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

Pattern.compile("\\S").asPredicate();

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

Pattern.compile("^\\s*$").asPredicate().negate();

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[i]);
            sb.append(separator);
        }
    }
    sb.append(data[data.length - 1].trim());
    return sb.toString();
}

You can use it like

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

or

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

Output ab, abs

Solution 2 - Java

Why so serious? Try StringUtils.join(new String[] {"Hello", "World", "!"}, ", ") !

Solution 3 - Java

Here is an Android-specific answer that may be helpful to some:

String combined = TextUtils.join(",", new String[]{"Red", "Green", "Blue"});

// Result => Red,Green,Blue

Be sure to import the TextUtils class:

import android.text.TextUtils;

Solution 4 - Java

You'd have to add your strings to an ArrayList, remove empty ones, and format it accordingly:

public static String createAddressString( String street, String zip_code, String country) {
    List<String> list = new ArrayList<String>();
    list.add( street);
    list.add( zip_code);
    list.add( country);

    // Remove all empty values
    list.removeAll(Arrays.asList("", null));

    // If this list is empty, it only contained blank values
    if( list.isEmpty()) {
        return "";
    }

    // Format the ArrayList as a string, similar to implode
    StringBuilder builder = new StringBuilder();
    builder.append( list.remove(0));

    for( String s : list) {
        builder.append( ", ");
        builder.append( s);
    }

    return builder.toString();
}

Additionally, if you had String[], an array of strings, you can easily add them to an ArrayList:

String[] s;
List<String> list = new ArrayList<String>( Arrays.asList( s));

Solution 5 - Java

Using Streams (for Java 8 and later) would be an alternate possible solution for this.

You are required to import

java.util.stream.Collectors;

to use the join process

You may use:

Arrays.asList("foo","bar").stream().collect(Collectors.joining(","));

to achieve the desired result.

Solution 6 - Java

A simple Implode

public static String implode(String glue, String[] strArray)
{
	String ret = "";
	for(int i=0;i<strArray.length;i++)
    {
		ret += (i == strArray.length - 1) ? strArray[i] : strArray[i] + glue;
	}
	return ret;
}

You can create overloads for it..

The above it equivalent of php implode.
Here is what you want:

import java.lang.*
public static String customImplode(String glue, String[] strArray)
{
	String ret = "";
	for(int i=0;i<strArray.length;i++)
	{
		if (strArray[i].trim() != "")
			ret += (i == strArray.length - 1) ? strArray[i] : strArray[i] + glue;
	}
	return ret;
}

Solution 7 - Java

Here's my implode implementation:

/**
 * Implodes the specified items, gluing them using the specified glue replacing nulls with the specified
 * null placeholder.
 * @param glue              The text to use between the specified items.
 * @param nullPlaceholder   The placeholder to use for items that are <code>null</code> value.
 * @param items             The items to implode.
 * @return  A <code>String</code> containing the items in their order, separated by the specified glue.
 */
public static final String implode(String glue, String nullPlaceholder, String ... items) {
    StringBuilder sb = new StringBuilder();
    for (String item : items) {
        if (item != null) {
            sb.append(item);
        } else {
            sb.append(nullPlaceholder);
        }
        sb.append(glue);
    }
    return sb.delete(sb.length() - glue.length(), sb.length()).toString();
}

Solution 8 - Java

public static String implode(List<String> items, String separator) {

        if (items == null || items.isEmpty()) {
            return null;
        }
        String delimiter = "";
        StringBuilder builder = new StringBuilder();
        for (String item : items) {
            builder.append(delimiter).append(item);
            delimiter = separator;
        }
        return builder.toString();
    }

Solution 9 - Java

Use this simple function:

private String my_implode(String spacer, String[] in_array){

    String res = "";

    for (int i = 0 ; i < in_array.length ; i++) {

        if (!res.equals("")) {
            res += spacer;
        }
        res += in_array[i];
    }

    return res;
}

Use:

data_arr = {"d1", "d2", "d3"};
your_imploded_text = my_implode(",", data_arr);
// Output: your_imploded_text = "d1,d2,d3"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmax4everView Question on Stackoverflow
Solution 1 - JavaPshemoView Answer on Stackoverflow
Solution 2 - JavaBogdan BurymView Answer on Stackoverflow
Solution 3 - JavadloombView Answer on Stackoverflow
Solution 4 - JavanickbView Answer on Stackoverflow
Solution 5 - JavaAman JView Answer on Stackoverflow
Solution 6 - JavaSoroush KhosraviView Answer on Stackoverflow
Solution 7 - JavaBen BarkayView Answer on Stackoverflow
Solution 8 - JavaAhmadView Answer on Stackoverflow
Solution 9 - JavaFerhad KonarView Answer on Stackoverflow