Convert List of String> to List of Object java

InJava, we have a lot of ways to convert List of String object to String object with a delimiter between the elements in List object. In this tutorial, I will share with you all some ways as below:

The first one, we will use StringBuilder object in Java.

We will read all elements in the List, one by one and useStringBuilderto add the delimiter among all elements. Note that, with the first element, we will not add the delimiter!

In detail, the method can be written as below:

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static String join(List list, char delimiter) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
if (i == 0) {
sb.append(s);
continue;
}
sb.append(delimiter + s);
}
return sb.toString();
}

Example:

Convert List of String> to List of Object java

The second one, we will use collect() method of Stream object which was introduced since Java 8.

Java
1
2
3
public static String join(List list, char delimiter) {
return list.stream().collect(Collectors.joining(String.valueOf(delimiter)));
}

Example:

Convert List of String> to List of Object java

The third one, we will use join() static method of String object.

Since Java 8, Java introduced a new method named join() in String object, help us can convert from List object to String object easily.

Java
1
2
3
public static String join(List list, char delimiter) {
return String.join(String.valueOf(delimiter), list);
}

Example:

Convert List of String> to List of Object java

Finally, we can use an existing libraryApache Commons Langof Apache Foundation.

This libraryprovides a static method, namedjoin()in StringUtils classto help us can convert a List object to String object simply and easily. Because of its static method, then we only need call:

Java
1
StringUtils.join(List list, char delimiter);

Example:

Convert List of String> to List of Object java