This example will show how to print a list of objects separating each element with a comma using java, java 8, guava, apache commons and spring framework. In the set up method we will define a list using guava's List collection utility named programmingLanguages and the expected output in string variable named languagesSeperatedByComma.
Setup
private List<String> programmingLanguages = Lists.newArrayList("java", "python", "ruby", "groovy");
private String languagesSeperatedByComma = "java,python,ruby,groovy";
Straight up Java
This snippet will show how to print out all the elements of a list separating them with a comma using straight up java. The join method will accept a separator and vararg of strings to join together. The test method will call join passing in the ArrayList and a comma as a separator.
private static String join(String separator, String... strings) {
if (strings == null || strings.length == 0) {
return "";
} else if (strings.length == 1) {
return strings[0];
} else {
StringBuilder sb = new StringBuilder();
sb.append(strings[0]);
for (int i = 1; i < strings.length; i++) {
sb.append(separator).append(strings[i]);
}
return sb.toString();
}
}
@Test
public void join_elements_in_list_java () {
String elementsJoined = join(",", programmingLanguages.toArray(new String[programmingLanguages.size()]));
assertEquals(languagesSeperatedByComma, elementsJoined);
}
Java 8
Using java 8 string joiner we will join a stream using Collectors.joining which will concatenates the input elements separated by specified delimiter, in this case a comma.
@Test
public void join_elements_in_list_java8 () {
String elementsJoined = programmingLanguages
.stream()
.collect(Collectors.joining(","));
assertEquals(languagesSeperatedByComma, elementsJoined);
}
Google Guava
This snippet will show how to join a collection of strings separating each element by a comma using Guava's Joiner object which joins pieces of text with a separator.
@Test
public void join_elements_in_list_guava () {
String elementsJoined = Joiner.on(",").join(programmingLanguages);
assertEquals(languagesSeperatedByComma, elementsJoined);
}
Apache Commons
This snippet will demonstrate how to convert a programmingLanguages arraylist into a comma separated value string using apache commons StringUtils.join. It will join the elements of the provided Iterable into a single String.
@Test
public void join_elements_in_list_apache_commons () {
String elementsJoined = StringUtils.join(programmingLanguages, ",");
assertEquals(languagesSeperatedByComma, elementsJoined);
}
Spring Framework
Springs implementation StringUtils.collectionToDelimitedString provides the same behavior above. This connivence method will return a arraylist as a string separated by a comma.
@Test
public void join_elements_in_list_spring () {
String elementsJoined = org.springframework.util
.StringUtils.collectionToDelimitedString(programmingLanguages, ",");
assertEquals(languagesSeperatedByComma, elementsJoined);
}