In Java, 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 use StringBuilder to 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public static String join(List<String> 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:
The second one, we will use collect() method of Stream object which was introduced since Java 8.
1 2 3 |
public static String join(List<String> list, char delimiter) { return list.stream().collect(Collectors.joining(String.valueOf(delimiter))); } |
Example:
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.
1 2 3 |
public static String join(List<String> list, char delimiter) { return String.join(String.valueOf(delimiter), list); } |
Example:
Finally, we can use an existing library Apache Commons Lang of Apache Foundation.
This library provides a static method, named join() in StringUtils class to help us can convert a List object to String object simply and easily. Because of its static method, then we only need call:
1 |
StringUtils.join(List list, char delimiter); |
Example: