patternjavaCritical
A quick and easy way to join array elements with a separator (the opposite of split) in Java
Viewed 0 times
arrayquickwithjavaandsplitthejoinwayopposite
Problem
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
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?
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?
Solution
Using Java 8 you can do this in a very clean way:
This works in three ways:
1) directly specifying the elements
2) using arrays
3) using iterables
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 list = Arrays.asList(array);
String joined3 = String.join(",", list);Code Snippets
String.join(delimiter, elements);String joined1 = String.join(",", "a", "b", "c");String[] array = new String[] { "a", "b", "c" };
String joined2 = String.join(",", array);List<String> list = Arrays.asList(array);
String joined3 = String.join(",", list);Context
Stack Overflow Q#1978933, score: 969
Revisions (0)
No revisions yet.