Java Function for Arrays Like PHP's Join()

Java function for arrays like PHP's join()?

Starting from Java8 it is possible to use String.join().

String.join(", ", new String[]{"Hello", "World", "!"})

Generates:

Hello, World, !

Otherwise, Apache Commons Lang has a StringUtils class which has a join function which will join arrays together to make a String.

For example:

StringUtils.join(new String[] {"Hello", "World", "!"}, ", ")

Generates the following String:

Hello, World, !

A quick and easy way to join array elements with a separator (the opposite of split) in Java

Using Java 8 you can do this in a very clean way:

String.join(delimiter, elements);

This works in three ways:

1) directly specifying the elements

String joined1 = String.join(",", "a", "b", "c");

2) using arrays

String[] array = new String[] { "a", "b", "c" };
String joined2 = String.join(",", array);

3) using iterables

List<String> list = Arrays.asList(array);
String joined3 = String.join(",", list);

Java: join array of primitives with separator

Here what I came up with. There are several way to do this and they are depends on the tools you using.


Using StringUtils and ArrayUtils from Common Lang:

int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
String result = StringUtils.join(ArrayUtils.toObject(arr), " - ");

You can't just use StringUtils.join(arr, " - "); because StringUtils doesn't have that overloaded version of method. Though, it has method StringUtils.join(int[], char).

Works at any Java version, from 1.2.


Using Java 8 streams:

Something like this:

int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
String result = Arrays.stream(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining(" - "));

In fact, there are lot of variations to achive the result using streams.

Java 8's method String.join() works only with strings, so to use it you still have to convert int[] to String[].

String[] sarr = Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new);
String result = String.join(" - ", sarr);

If you stuck using Java 7 or earlier with no libraries, you could write your own utility method:

public static String myJoin(int[] arr, String separator) {
if (null == arr || 0 == arr.length) return "";

StringBuilder sb = new StringBuilder(256);
sb.append(arr[0]);

//if (arr.length == 1) return sb.toString();

for (int i = 1; i < arr.length; i++) sb.append(separator).append(arr[i]);

return sb.toString();
}

Than you can do:

int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
String result = myJoin(arr, " - ");

How to merge contents of an array?

String[] myStringArray = new String[]{"x", "a", "r", "y"};
StringBuilder builder = new StringBuilder();
for(String s:myStringArray)
builder.append(s);

System.out.println(builder );

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

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

Is there an Iterator-like function (or workaround) for Arrays?

Do you need something like that ?

String[] configs = config.split("");
String [][] endState = new String[4][4];
int i = 17;
for(int r=0;r<endState.length;r++){
for(int c=0;c<endState.length;c++){
endState[r][c] = configs[i++];
}
}

Join array values and keys between two php arrays

You can do this using array_walk with closure see example below :

$keyArray = [ "key1" => "map1", "key2" => "map1", "key3" => "map2", "key4" => "map3" ];

$valueArray = [ "key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value3" ];

function getMergeByKeys($keyArray, $valueArray) {
$mapped = [];
array_walk(
$keyArray,
function($key, $value) use ($valueArray, &$mapped) {
$mapped[$key][] = $valueArray[$value];
});
return $mapped;
}

print_r(getMergeByKeys($keyArray, $valueArray));

It will result :

Array
(
[map1] => Array
(
[0] => value1
[1] => value2
)

[map2] => Array
(
[0] => value3
)

[map3] => Array
(
[0] => value3
)

)

Java ArrayList String to single string without using loop

You could make a stream out of your list and collect it using joining collector :

list.stream().collect(Collectors.joining());

You can pass the separator to Collectors::joining method for example :

list.stream().collect(Collectors.joining("-"));

Or you can use String::join method :

String result = String.join(",", list);

where , is the separator.



Related Topics



Leave a reply



Submit