Thursday, July 22, 2021

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

Here is how you do it :
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<String> fixedLenghtList = Arrays.asList(elements);

// step three : copy fixed list to an ArrayList
ArrayList<String> listOfString = new ArrayList<String>(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.


How to convert comma separated String to ArrayList in Java - Example Tutorial

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.

CSV String to an ArrayList in 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 in Java




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<String> fixedLenghtList = Arrays.asList(elements);

// step three : copy fixed list to an ArrayList
ArrayList<String> listOfString = new ArrayList<String>(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.

Further Learning
How to remove duplicates from ArrayList in Java?
How to reverse an ArrayList in Java?
What is the difference between Vector and ArrayList in Java?
When to use ArrayList and LinkedList in Java?

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

5 comments:

  1. Hi,

    I have written a program based on ur explanation and tried to add element after creating copy arraylist see the program and result and please explain y the new item not added into list.

    public class ArraytoArrayList {

    public void StringToArrayLsit(String str){

    String[] stringArray= str.split(",");

    List stringList = Arrays.asList(stringArray);
    System.out.println("List Before ADD : " +stringList);

    ArrayList CopyList =new ArrayList<>(stringList);
    CopyList.add("test");

    System.out.println("List After ADD : " +stringList);

    }

    public static void main(String[] args) {
    String str = "java,j2ee,core java";
    ArraytoArrayList aal=new ArraytoArrayList();
    aal.StringToArrayLsit(str);
    }

    }

    Result:
    List Before ADD : [java, j2ee, core java]
    List After ADD : [java, j2ee, core java]

    why "test" is not added into list ?

    ReplyDelete
  2. Good for explanation, but still teaching wasting RAM. Don't instantiate temporary variables if not needed.

    List los = Arrays.asList( commaSeparatedList );

    Wham bam done.

    Java has a very finite amount of memory to save data. Don't waste it on nonessential instantiation of classes.

    ReplyDelete
  3. can we use the same methodology to create an object list from the comma separated string?

    ReplyDelete
    Replies
    1. Yes, definitely, just write code to convert String to your object that's it.

      Delete
  4. The output elements are a single space, what is your problem?
    Output: "[Apple, Google, Samsung]" — Google and Samsung with one space.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.