How to convert comma-separated String to List?
JavaStringCollectionsSplitJava Problem Overview
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";
List<String> items = //method that converts above string into list??
Java Solutions
Solution 1 - Java
Convert comma separated String to List
List<String> 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.
Please note that this returns simply a wrapper on an array: you CANNOT for example .remove()
from the resulting List
. For an actual ArrayList
you must further use new ArrayList<String>
.
Solution 2 - Java
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<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));
Or, using Guava:
List<String> 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).
Solution 3 - Java
Two steps:
String [] items = commaSeparated.split("\\s*,\\s*");
List<String> container = Arrays.asList(items);
Solution 4 - Java
List<String> items= Stream.of(commaSeparated.split(","))
.map(String::trim)
.collect(Collectors.toList());
Solution 5 - Java
If a List
is the end-goal as the OP stated, then already accepted answer is still the shortest and the best. However I want to provide alternatives using Java 8 Streams, that will give you more benefit if it is part of a pipeline for further processing.
By wrapping the result of the .split function (a native array) into a stream and then converting to a list.
List<String> list =
Stream.of("a,b,c".split(","))
.collect(Collectors.toList());
If it is important that the result is stored as an ArrayList
as per the title from the OP, you can use a different Collector
method:
ArrayList<String> list =
Stream.of("a,b,c".split(","))
.collect(Collectors.toCollection(ArrayList<String>::new));
Or by using the RegEx parsing api:
ArrayList<String> list =
Pattern.compile(",")
.splitAsStream("a,b,c")
.collect(Collectors.toCollection(ArrayList<String>::new));
Note that you could still consider to leave the list
variable typed as List<String>
instead of ArrayList<String>
. The generic interface for List
still looks plenty of similar enough to the ArrayList
implementation.
By themselves, these code examples do not seem to add a lot (except more typing), but if you are planning to do more, like this answer on converting a String to a List of Longs exemplifies, the streaming API is really powerful by allowing to pipeline your operations one after the other.
For the sake of, you know, completeness.
Solution 6 - Java
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.size();i++)
{
System.out.println(" -->"+aList.get(i));
}
Prints you
> -->string
-->with
-->comma
Solution 7 - Java
List<String> items = Arrays.asList(commaSeparated.split(","));
That should work for you.
Solution 8 - Java
There is no built-in method for this but you can simply use split() method in this.
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items =
new ArrayList<String>(Arrays.asList(commaSeparated.split(",")));
Solution 9 - Java
you can combine asList and split
Arrays.asList(CommaSeparated.split("\\s*,\\s*"))
Solution 10 - Java
This code will help,
String myStr = "item1,item2,item3";
List myList = Arrays.asList(myStr.split(","));
Solution 11 - Java
You can use Guava to split the string, and convert it into an ArrayList. This works with an empty string as well, and returns an empty list.
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
String commaSeparated = "item1 , item2 , item3";
// Split string into list, trimming each item and removing empty items
ArrayList<String> list = Lists.newArrayList(Splitter.on(',').trimResults().omitEmptyStrings().splitToList(commaSeparated));
System.out.println(list);
list.add("another item");
System.out.println(list);
outputs the following:
[item1, item2, item3]
[item1, item2, item3, another item]
Solution 12 - Java
There are many ways to solve this using streams in Java 8 but IMO the following one liners are straight forward:
String commaSeparated = "item1 , item2 , item3";
List<String> result1 = Arrays.stream(commaSeparated.split(" , "))
.collect(Collectors.toList());
List<String> result2 = Stream.of(commaSeparated.split(" , "))
.collect(Collectors.toList());
Solution 13 - Java
An example using Collections
.
import java.util.Collections;
...
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = new ArrayList<>();
Collections.addAll(items, commaSeparated.split("\\s*,\\s*"));
...
Solution 14 - Java
You can first split them using String.split(",")
, and then convert the returned String array
to an ArrayList
using Arrays.asList(array)
Solution 15 - Java
In groovy, you can use tokenize(Character Token) method:
list = str.tokenize(',')
Solution 16 - Java
Same result you can achieve using the Splitter class.
var list = Splitter.on(",").splitToList(YourStringVariable)
(written in kotlin)
Solution 17 - Java
While this question is old and has been answered multiple times, none of the answers is able to manage the all of the following cases:
""
-> empty string should be mapped to empty list" a, b , c "
-> all elements should be trimmed, including the first and last element",,"
-> empty elements should be removed
Thus, I'm using the following code (using org.apache.commons.lang3.StringUtils
, e.g. https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.11):
StringUtils.isBlank(commaSeparatedEmailList) ?
Collections.emptyList() :
Stream.of(StringUtils.split(commaSeparatedEmailList, ','))
.map(String::trim)
.filter(StringUtils::isNotBlank)
.collect(Collectors.toList());
Using a simple split expression has an advantage: no regular expression is used, so the performance is probably higher. The commons-lang3
library is lightweight and very common.
Note that the implementation assumes that you don't have list element containing comma (i.e. "a, 'b,c', d"
will be parsed as ["a", "'b", "c'", "d"]
, not to ["a", "b,c", "d"]
).
Solution 18 - Java
Java 9 introduced List.of():
String commaSeparated = "item1 , item2 , item3";
List<String> items = List.of(commaSeparated.split(" , "));
Solution 19 - Java
List commaseperated = new ArrayList();
String mylist = "item1 , item2 , item3";
mylist = Arrays.asList(myStr.trim().split(" , "));
// enter code here
Solution 20 - Java
I usually use precompiled pattern for the list. And also this is slightly more universal since it can consider brackets which follows some of the listToString expressions.
private static final Pattern listAsString = Pattern.compile("^\\[?([^\\[\\]]*)\\]?$");
private List<String> getList(String value) {
Matcher matcher = listAsString.matcher((String) value);
if (matcher.matches()) {
String[] split = matcher.group(matcher.groupCount()).split("\\s*,\\s*");
return new ArrayList<>(Arrays.asList(split));
}
return Collections.emptyList();
Solution 21 - Java
List<String> items = Arrays.asList(s.split("[,\\s]+"));
Solution 22 - Java
In Kotlin if your String list like this and you can use for convert string to ArrayList use this line of code
var str= "item1, item2, item3, item4"
var itemsList = str.split(", ")
Solution 23 - Java
In java, It can be done like this
String catalogue_id = "A, B, C";
List<String> catalogueIdList = Arrays.asList(catalogue_id.split(", [ ]*"));
Solution 24 - Java
You can do it as follows.
This removes white space and split by comma where you do not need to worry about white spaces.
String myString= "A, B, C, D";
//Remove whitespace and split by comma
List<String> finalString= Arrays.asList(myString.split("\\s*,\\s*"));
System.out.println(finalString);
Solution 25 - Java
String -> Collection conversion: (String -> String[] -> Collection)
// java version 8
String str = "aa,bb,cc,dd,aa,ss,bb,ee,aa,zz,dd,ff,hh";
// Collection,
// Set , List,
// HashSet , ArrayList ...
// (____________________________)
// || ||
// \/ \/
Collection<String> col = new HashSet<>(Stream.of(str.split(",")).collect(Collectors.toList()));
Collection -> String[] conversion:
String[] se = col.toArray(new String[col.size()]);
String -> String[] conversion:
String[] strArr = str.split(",");
And Collection -> Collection:
List<String> list = new LinkedList<>(col);
Solution 26 - Java
convert Collection into string as comma seperated in Java 8
listOfString object contains ["A","B","C" ,"D"] elements-
listOfString.stream().map(ele->"'"+ele+"'").collect(Collectors.joining(","))
Output is :- 'A','B','C','D'
And Convert Strings Array to List in Java 8
String string[] ={"A","B","C","D"};
List<String> listOfString = Stream.of(string).collect(Collectors.toList());
Solution 27 - Java
ArrayList<HashMap<String, String>> mListmain = new ArrayList<HashMap<String, String>>();
String marray[]= mListmain.split(",");