How to Join a List of Strings By a Delimiter in Java
Suppose we have an ArrayList
, and we want to join all the elements together by some character, or delimiter.
List<String> list = Arrays.asList("a","b","c");
Let’s say we want to join these elements with commas to create the string: a,b,c
.
1. Join a list using String.join()
We can easily use String.join()
to concatenate multiple strings by a delimiter, which is specified in the first parameter.
String res = String.join(",", list);
2. Join a list using the Stream API
We can use the Stream API’s Collectors.joining()
method to achieve the same functionality.
String res = list.stream().collect(Collectors.joining(","));
3. Join a list using StringJoiner
The third option is to scrap the list entirely.
If we know that all we want to do is join the elements into a string, then we can use StringJoiner
from the get-go.
StringJoiner joiner = new StringJoiner(",");
joiner.add("a");
joiner.add("b");
joiner.add("c");
String res = joiner.toString();