How to Convert a Comma Separated String to an ArrayList in Java — Example Tutorial
Suppose you have a comma-separated list of String e.g. «Samsung, Apple, Sony, Google, Microsoft, Amazon» and you want to convert it into an ArrayList containing all String elements e.g. Samsung, Apple, Google, etc. How do you do that? Well, Java doesn’t provide any such constructor or factory method to create ArrayList from delimited String, but you can use String.split() method and Arrays.asList() method together to create an ArrayList from any delimited String, not just comma separated one.
All you need to do is first split the given String on delimiter e.g. comma using the split() method, this will give you an array of String. Now, you can pass that array to Arrays.asList() method to create a list, but remember this would be a fixed-length list and not truly an ArrayList.
There is one more step to follow, just create an ArrayList by passing this fixed length list, Collection provides a copy constructor, which will copy all elements from that list to your new ArrayList, which would be regular ArrayList, where you can add, remove and update elements.
Let’s see it in action. btw, if you want to parse a CSV file in Java and not just a single String then please see that article for a solution. Though it’s not very common to create an ArrayList like that, it may be required if you are getting the String from outside of your application e.g. a database, a web service, or from an upstream system.
I also suggest creating a utility method to do this task in your code and encapsulate the logic there. This way, you can use it wherever you want to use this logic, without always recreating it from scratch.
If you are working in a big organization e.g. Investment banks, chances are that you already have a library that may contain these kinds of methods. So, you should first find them before creating your own method.
Steps to convert a comma Separated String to ArrayList
There are three steps to convert a comma-separated String to list of String objects in Java :
1) Split the comma-delimited String to create String array — use String.split() method
2) Convert String Array to List of String — use Arrays.asList() method
3) Create an ArrayList by copying contents from fixed length list — Use ArrayList constructor
String csv = "Apple, Google, Samsung"; // step one : converting comma separate String to array of String String[] elements = csv.split(","); // step two : convert String array to list of String List fixedLenghtList = Arrays.asList(elements); // step three : copy fixed list to an ArrayList ArrayList listOfString = new ArrayList(fixedLenghtList); System.out.println("list from comma separated String : " + listOfString); System.out.println("size of ArrayList : " + listOfString.size()); Output : list of comma separated String : [Apple, Google, Samsung] size of ArrayList : 3
You can see that our list contains 3 elements which are correct given our CSV String. By the way, you should remember that the list we created in step 2 is a fixed length List i.e. you cannot change its length, which effectively means you cannot add or remove any elements, that’s why we have created another ArrayList . See Java Collections Fundamentals by Richard Warburton to learn more about such peculiarities of different collection classes in Java.
Another thing, which is worth knowing is that String.split() method accepts a regular expression.
For example, in our example «,» says match any comma and split on that, but this will not trim any leading or trailing space. That’s why the String we have got is not exactly «Google» but » Google» see the leading space there.
If you want to get rid of those leading and trailing space without using trim() with every element in String array, you can fine-tune your regular expression a bit. Instead of using «,» you can use «\\s*,\\s*» . The regex may look daunting but its really easy to understand if you know basic.
The \s is used to match any whitespace, including tabs and * means any number of times. That mean \s* will match zero or more whitespace.
Since we need to escape \ in Java, «\s» becomes «\\s*» . Now if you look our regular expression again, it is nothing but «\\s*» + «,» + «\\s*» , which means any number of whitespace then a comma, and then again any number of whitespace.
So, you will match both leading and trail whitespace with a comma. If you want to learn regular expression in more detail, I suggest The Complete Java MasterClass course from Udemy, which explains advanced concepts of Java e.g. regular expression. It is also updated for Java 11, the latest version of Java.
If we run the same program with our improved regular expression for splitting String, you will get the following output :
list of comma separated String : [Apple, Google, Samsung] size of ArrayList : 3
You can see there is no leading space in Google and Samsung, as it was the case earlier. It will also work with varying CSV string e.g. «Android, Chrome, Windows» will also give the same output, as seen below :
list of comma-separated String : [Android, Chrome, Windows]
Btw, you must remember that this pattern will only remove leading and trailing space between commas, which means if you have leading space in the first element and trailing space in the last element that will not be removed e.g. » XBOX, PlayStation, Gameboy » will print
list of comma-separated String : [ XBOX, PlayStation, Gameboy ]
You can see the leading space with the first String and the training space with the last String. If the Regular expression is your week point and you have trouble both understanding Regular expression and creating new ones based upon your requirements then I suggest you check Complete Regular Expressions Bootcamp — Go from zero to hero course on Udemy. It’s one of the best materials to get up-to-speed on regex and will help you become a better developer.
Delimited String to ArrayList Conversion
The logic and steps we have learned are not just applicable to comma-separated String, in fact, you can use them to convert any delimited String into an array or list e.g. a pipe-delimited string, colon-delimited String, or any other arbitrary delimiter.
Here is an example of creating ArrayList from pipe and column delimited String :
String csv = "Java|Ruby|Python|Perl"; // step one : converting pipe separate String to array of String // pipe is special character in regex, to use it literally enclose in // bracket String[] elements = csv.split("\\s*[|]\\s*"); // step two : convert String array to list of String List fixedLenghtList = Arrays.asList(elements); // step three : copy fixed list to an ArrayList ArrayList listOfString = new ArrayList (fixedLenghtList); System.out.println("list from pipe delimitedd String : " + listOfString); Output : list from the pipe delimited String : [Java, Ruby, Python, Perl]
This example is exactly similar to the previous example but here we have used PIPE (|) as a delimiter than a comma (,). This also brings a new thing, since PIPE has special meaning in regex (OR condition, see Core Java for the Impatient), you need to enclose it within the bracket to use it literally, otherwise, you will get different output.
That’s all about how to convert comma-separated String to ArrayList in Java. You can use the steps given here to convert any delimited String e.g. pipe or colon-delimited to list or array. Just remember that split() method of the String class accepts a regular expression, which can be tricky if you are not familiar with it.
Second, the list returned by Arrays.asList() method is a fixed-length list and you cannot add or remove elements from it, that’s why we have created a regular ArrayList by copying contents from there.
Thanks for reading this article, if you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please let me know
Convert a comma-separated string to a list in Java
There are many ways to convert a comma-separated string into a list in Java. In this article, we’ll look at three different methods to convert a string with a separator to a list.
The String class in Java provides split() method to split a string into an array of strings. You can use this method to turn the comma-separated list into an array:
String fruits = "🍇,🍓,🍑,🥭,🍍,🥑"; String [] fruitsArray = fruits.split(",");
ListString> fruitsList = Arrays.asList(fruitsArray);
String fruits = "🍇,🍓,🍑,🥭,🍍,🥑"; ListString> fruitsList = Arrays.asList(fruits.split(",")); System.out.println(fruitsList); // [🍇, 🍓, 🍑, 🥭, 🍍, 🥑]
If the comma-separated string contains white spaces, you can pass a regular expression to split() to remove them:
String fruits = "🍇, 🍓, 🍑, 🥭, 🍍, 🥑"; ListString> fruitsList = Arrays.asList(fruits.split("\\s*,\\s*"));
String fruits = "🍇, 🍓, 🍑, 🥭, 🍍, 🥑"; ListString> fruitsList = Stream.of(fruits.split("\\s*,\\s*")) .collect(Collectors.toList()); System.out.println(fruitsList); // [🍇, 🍓, 🍑, 🥭, 🍍, 🥑]
In the above example, we first used the split() method to convert our fruits string into an array of strings. Then, we used the Stream class to convert the array into a list of strings. An additional benefit of using Java Stream API is that you can perform other operations on the elements of the array before converting them into a list. Look at the following example that converts a string of numbers into a list of integers using a stream:
String numbers = "23, 45, 2, 7, 99, 6"; ListInteger> list = Stream.of(numbers.split(",")) .map(String::trim) .map(Integer::parseInt) .collect(Collectors.toList()); System.out.println(list); // [23, 45, 2, 7, 99, 6]
The first part of the example is the same, convert a comma-separated string of numbers into an array. Then, it trims the leading and trailing spaces from each string on the stream using the map(String::trim) method. Next, the map(Integer::parseInt) method is called on our stream to convert every string to an Integer . Finally, it calls the collect(Collectors.toList()) method on the stream to transform it into an integer list.
Apache Commons Lang is an open-source library that provides many utility classes to manipulate core Java classes. One such utility class is the StringUtils that offers utility methods for string operations. To add Commons Lang to your Maven project, add the following dependency to the pom.xml file:
dependency> groupId>org.apache.commonsgroupId> artifactId>commons-lang3artifactId> version>3.12.0version> dependency>
implementation 'org.apache.commons:commons-lang3:12.0'
Now you can use the StringUtils.splitPreserveAllTokens() method to convert the string into an array of strings:
String[] fruitsArray = StringUtils.splitPreserveAllTokens(fruits, ",");
ListString> fruitsList = Arrays.asList(fruitsArray);
Both split() and splitPreserveAllTokens() methods split the string into an array of strings using a delimiter. However, the splitPreserveAllTokens() method preserves all tokens, including the empty strings created by adjoining separators, while the split() method ignores empty strings. Read Next: Convert a list to a comma-separated string in Java ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.