Tuesday, December 1, 2020

How to Create List of String to Comma Separated String.

This is a short tutorial to show how to convert the list of strings into the comma-separated string.

1. In Java 8 and later:

- Using String.join() method.
import java.util.Arrays;
import java.util.List;

public class JavaStringJoin {
    public static void main(String[] args) {
        List <String> stringList = Arrays.asList("apple","banana","grapes");
        String joinedString = String.join(",", stringList);
        System.out.println(joinedString);
    }
}
Output:
apple,banana,grapes
This will simply join each element of the list with the delimiter provided. Here, we are providing "," as a delimiter. If the element present in the list is null then it will join the "null" to the string. If the delimiter is null then, it will throw Null Pointer Exception.

- Using stream API:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class JavaStringJoin {
    public static void main(String[] args) {
        List <String> stringList = Arrays.asList("apple","banana","grapes");
        String joinedString = stringList.stream().collect(Collectors.joining(","));
        System.out.println(joinedString);
    }
}
  
- Using StringJoiner:
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;

public class JavaStringJoin {
    public static void main(String[] args) {
        List <String> stringList = Arrays.asList("apple","banana","grapes");
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String element : stringList){
            stringJoiner.add(element);
        }
        System.out.println(stringJoiner.toString());
    }
}
  
Actually, String.join() uses this StringJoiner mechanism.

The output will be the same as the previous example.

2. You can use StringBuilder to build the concatenated string:

import java.util.Arrays;
import java.util.List;

public class JavaStringJoin {
    public static void main(String[] args) {
        List <String> stringList = Arrays.asList("apple","banana","grapes");
        StringBuilder stringBuilder = new StringBuilder();
        int size = stringList.size();
        for (int i = 0; i < size; i++) {
            stringBuilder.append(stringList.get(i));
            if (i < size -1){
                stringBuilder.append(",");
            }
        }
        System.out.println(stringBuilder.toString());
    }
}

3. If you are using Apache's commons library, you can use StringUtils.join() method.

String joinedString = StringUtils.join(stringList, ",")
Share:

0 comments: