Organizational Research By

Surprising Reserch Topic

how to convert comma separated string to arraylist


how to convert comma separated string to arraylist  using -'java,string,collections,split'

Is there any built-in method in Java which allows us to convert comma separated String to some container (e.g array, List or Vector)? Or do I need to write custom code for that?

String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = //method that converts above string into list??

    

asked Sep 30, 2015 by shegokar.anjeet
0 votes
10 views



Related Hot Questions

7 Answers

0 votes

Convert comma separated String to ArrayList

List items = Arrays.asList(str.split("\\s*,\\s*"));

The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace which will place the words into the list and collapse any whitespace between the words and commas.

answered Sep 30, 2015 by vimaldas2005
0 votes

Arrays.asList returns a fixed-size List backed by the array. If you want a normal mutable java.util.ArrayList you need to do this:

List list = new ArrayList(Arrays.asList(string.split(" , ")));

Or, using Guava:

List list = Lists.newArrayList(Splitter.on(" , ").split(string));

Using a Splitter gives you more flexibility in how you split the string and gives you the ability to, for example, skip empty strings in the results and trim results. It also has less weird behavior than String.split as well as not requiring you to split by regex (that's just one option).

answered Sep 30, 2015 by loknath.ganji
0 votes

Here is another one for converting CSV to ArrayList:

String str="string,with,comma";
ArrayList aList= new ArrayList(Arrays.asList(str.split(",")));
for(int i=0;i"+aList.get(i));
}

Prints you

-->string
-->with
-->comma

answered Sep 30, 2015 by mca.agarwal
0 votes

There is no built-in method for this but you can simply use split() method in this.

String commaSeparated = "item1 , item2 , item3";
ArrayList items = 
new  ArrayList(Arrays.asList(commaSeparated.split(",")));
answered Sep 30, 2015 by yashwantpinge
0 votes

This below code may help you,

List myList = new ArrayList();
String myStr = "item1 , item2 , item3";
myList = Arrays.asList(myStr.split(" , "));
answered Sep 30, 2015 by ashish singh
0 votes

An example using Collections.

import java.util.Collections;
 ...
String commaSeparated = "item1 , item2 , item3";
ArrayList items = new ArrayList<>();
Collections.addAll(items, commaSeparated.split("\\s*,\\s*"));
 ...
answered Sep 30, 2015 by rajeshujade
0 votes

List commaseperated = new ArrayList(); String mylist = "item1 , item2 , item3"; mylist = Arrays.asList(myStr.trim().split(" , "));`//enter code here

answered Sep 30, 2015 by param.oncemore

...