Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

See Related .NET question

I'm looking for a quick and easy way to do exactly the opposite of split so that it will cause ["a","b","c"] to become "a,b,c"

Iterating through an array requires either adding a condition (if this is not the last element, add the seperator) or using substring to remove the last separator.

I'm sure there is a certified, efficient way to do it (Apache Commons?)

How do you prefer doing it in your projects?

like image 391
Eran Medan Avatar asked Dec 30 '09 07:12

Eran Medan


People also ask

How do you split and join in Java?

A class named Demo contains the main function. Here a String object is defined and it is split based on the '_' value upto the last word. A 'for' loop is iterated over and the string is split based on the '_' value. Again, the string is joined using the 'join' function.

How do you combine elements in an array Java?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

Which method joins all array elements into string with specified separator?

join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.


1 Answers

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); 
like image 58
skiwi Avatar answered Dec 22 '22 22:12

skiwi