Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

php

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

like image 881
max4ever Avatar asked Jun 28 '12 15:06

max4ever


People also ask

What are use explode () implode () function?

The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.

How do you implode an array key?

$array = ['a very' => ['complex' => 'array']]; $imploded = var_export($array, true); This will return the exported var instead of directly printing it on the screen and the var $imploded will contain the full export.

What would implode explode string )) do?

As the name suggests Implode/implode() method joins array elements with a string segment that works as a glue and similarly Explode/explode() method does the exact opposite i.e. given a string and a delimiter it creates an array of strings separating with the help of the delimiter.

What is the first parameter of the implode () function?

The first parameter is 'separator' The separator is the optional parameter, and it is there to specify what is needed to be put between the array components. By default, it appears as ”, “ which denotes an empty string. The array values are joined to form a string and are separated by the separator parameter.


2 Answers

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

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

  • String.join(CharSequence delimiter, CharSequence... elements)

    • String.join(" > ", new String[]{"foo", "bar"});
    • String.join(" > ", "foo", "bar");

  • or String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

    • String.join(" > ", Arrays.asList("foo", "bar"));

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

like image 101
Pshemo Avatar answered Sep 19 '22 17:09

Pshemo


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

like image 40
Bogdan Burym Avatar answered Sep 20 '22 17:09

Bogdan Burym