sneppets-java8

Java : Convert comma separated String to List

This tutorial shows you how to convert comma separated String to List and vice versa.

Example 1: Convert Comma Separated String to List

package com.sneppets.example;

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

public class CSStringToListExample {
	
	public static void main (String[] args) {
		
		String str = "a,b,c,d";
		
		List<String> strList = Arrays.asList(str.split("\\s*,\\s*"));
		
		System.out.println(" Comma Separated String to List : " + strList);
	}

}

Output

Comma Separated String to List : [a, b, c, d]

Example 2 : Convert List to Comma Separated String

This example make use of String.join() for conversion and no need to loop through the List as shown below.

package com.sneppets.example;

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

public class ListToCSStringExample {
	
	public static void main (String[] args) {
		
		List<String> strList = Arrays.asList("a","b","c","d");
		
		String str = String.join(",", strList);
		
		System.out.println("List to Comma Separated String : " + str);
	}

}

Output

List to Comma Separated String : a,b,c,d

Note, String.join() returns a new String which has copies Charsequence elements that are passed as second argument with a copy of the delimiter (“,”) specified as first argument.

Further Learning

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments