0 votes
1 view
in Java by (3.4k points)

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

1 Answer

0 votes
by (27.4k points)

This is a very easy and clean method:

String.join(delimiter, elements);

This operates in three methods:

1) immediately defining the elements

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

2) applying arrays

String[] array = new String[] { "a", "b", "c" };

String joined2 = String.join(",", array);

3) applying iterables

List<String> list = Arrays.asList(array);

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

...