How to a Split CSV String in Java

Learn to split a CSV (comma-separated value) and store the tokens in an array or List in Java using simple and easy-to-follow examples.

1. Using Regular Expression

We can use a regular expression "\\s*,\\s*" to match commas in CSV string and then use String.split() method to convert string to an array of tokens.

String blogName = "how, to, do, in, java";
String[] tokenArray = blogName.split("\\s*,\\s*");

Assertions.assertArrayEquals(new String[]{"how", "to", "do", "in", "java"}, tokenArray);

Note that the rex takes care of extra unwanted spaces in the String and only tokenizes the proper strings. In the following example, notice the unwanted multiple spaces between the commas.

Assertions.assertArrayEquals(new String[]{"a", "b", "c"}, "a, b,c".split("\\s*,\\s*")); 
Assertions.assertArrayEquals(new String[]{"a", "b", "c"}, "a,   b,    c".split("\\s*,\\s*"));

3. Convert Array to List

To get the List of tokens, we can pass the array to Arrays.asList() method that returns a fixed-size, unmodifiable read-only list backed by the array.

List<String> tokenList = Arrays.asList(tokenArray);

To get the mutable arraylist, copy all elements from the read-only list received from the above example into a new ArrayList object.

ArrayList<String> tokenArrayList = new ArrayList(Arrays.asList(tokenArray));

3. Convert a List to CSV String

If we want to convert a List to CSV, then we can use String.join() method provided by Java 8.

List<String> list = Arrays.asList("how", "to", "do", "in", "java");
String result = String.join(",", list);    //delimited by comma
Assertions.assertEquals("how,to,do,in,java", result);

Above examples will help to convert CSV to List and List to CSV in Java.

Happy Learning !!

Read More:

Sourcecode on Github

Leave a Reply

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial