583

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??
Honza Zidek
  • 6,952
  • 4
  • 52
  • 82
Jame
  • 18,248
  • 32
  • 76
  • 102

25 Answers25

1089

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>.

Fattie
  • 30,632
  • 54
  • 336
  • 607
AlexR
  • 109,181
  • 14
  • 116
  • 194
  • 40
    @rosch Its a regular expression (regex). `\s` matches any white space, The `*` applies the match zero or more times. So `\s*` means "match any white space zero or more times". We look for this before and after the comma. Therefore, the split will work for strings like `"item1 , item2 , item3"`, or `"item1,item2 ,item3"`, etc. In Java, you need to escape the backslash in strings, so you get `\\s*` – andrewrjones Nov 14 '12 at 09:44
  • 10
    I suggest to use `"[\\s,]+"` to trim white spaces for values. For example, `" item1 , item2 , item3 , "` becomes `["item1", "item2", "item3"]`. – tellnobody Mar 21 '14 at 14:12
  • @andreyne `" item1 , item2 , item3 , ".split("[\\s,]+")` returns a `String[]` of length 4 - not 3 as expected. – Andrew Sep 03 '14 at 16:33
  • you have to add -1 as limit to the split("regex",limit)-Method, otherwise the empty cells at the end get truncated see: http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-int- – Bernhard Mar 24 '15 at 08:32
  • 1
    CSV can contain a comma within a quote. Example: `foo,"bar,baz",qux`. See this answer for a good regex in such situations: http://stackoverflow.com/a/1757107/1048340 – Jared Rummler Apr 01 '15 at 05:46
  • 5
    `"[\\s,]+"` will also split on internal space within a comma separated token, it will treat both whitespace as a delimiter even when a comma is not present, instead of a comma plus any number of surrounding whitespace. `"\\s*(,\\s*)+"` will trim whitespace only around comma separated tokens, and also ignore any strings that are only whitespace or empty. – theferrit32 Jul 29 '15 at 18:08
  • 3
    As a side note: if you expect to get an empty list in case of an empty input string, then this method does not suit your use case. You will get a list with 1 element containing an empty string. – Madis Pukkonen Sep 28 '16 at 11:53
  • 2
    @MadisPukkonen, you are absolutely right, but I respect the OP enough to assume that he can add such logic himself. – AlexR Sep 28 '16 at 18:50
  • 3
    @AlexR Although I appreciate that you respect the OP, but, I would refrain from saying such things. I know of people that feel bad for not meeting people's expectations when praised falsely. Just a thought. –  Oct 25 '17 at 21:33
216

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).

ColinD
  • 103,631
  • 27
  • 195
  • 199
  • 6
    Would have preferred **Splitter.on(",").trimResults().split(string)** although I see you did mention it. so +1 – John B Sep 20 '11 at 16:57
  • 10
    +1 for pointing out that Arrays.asList doesn't return a normal list. If you try to add or remove an element to/from that List you will get an UnsupportedOperationException. – Alfredo Osorio Sep 20 '11 at 17:02
  • 9
    Guava now has this since (15.0) : **Splitter.on(",").splitToList(string)**. Saves a small step. – Kango_V Jul 04 '16 at 20:16
  • Is there any way to also add empty values in String iike if I've String like this: 1,,3,4,5 here 2 is missing/empty. When converting in list 2 will skip. But I want to add this as empty value. – A.Aleem11 May 24 '18 at 02:56
  • The problem with this implementation, and some other similar examples, is that although the `Arrays.asList` provides a wrapper around the native array (avoiding an element copy), the `new ArrayList(...)` will exactly do such an element by element copy. We should probably prefer an approach that allows parsed elements to be directly added to the desired target collection. – YoYo Aug 29 '18 at 14:58
  • This one is the right answer. you can try on the online java compiler. https://www.compilejava.net/ – Asad Shakeel Dec 06 '19 at 16:45
74

Two steps:

  1. String [] items = commaSeparated.split("\\s*,\\s*");
  2. List<String> container = Arrays.asList(items);
duffymo
  • 293,097
  • 41
  • 348
  • 541
  • 1
    Once you inline the items variable, it is basically the same as other answers, but a bit more efficient actually since it doesn't use regex. On the flip side, spaces around the comma will kill this option. – Amrinder Arora Oct 06 '16 at 20:50
  • 4
    @AmrinderArora the argument to `split` is interpreted as a RegEx. – Madbreaks Mar 14 '17 at 18:01
29
List<String> items= Stream.of(commaSeparated.split(","))
     .map(String::trim)
     .collect(toList());
Manu
  • 2,798
  • 2
  • 22
  • 24
24

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

Prasad Jadhav
  • 4,786
  • 16
  • 57
  • 79
Arvindvp6
  • 261
  • 2
  • 3
24

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.

YoYo
  • 7,796
  • 8
  • 50
  • 67
15
List<String> items = Arrays.asList(commaSeparated.split(","));

That should work for you.

Jason Wheeler
  • 834
  • 9
  • 22
15

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(",")));
Ishara
  • 159
  • 3
10

you can combine asList and split

Arrays.asList(CommaSeparated.split("\\s*,\\s*"))
corsiKa
  • 76,904
  • 22
  • 148
  • 194
8

This code will help,

String myStr = "item1,item2,item3";
List myList = Arrays.asList(myStr.split(","));
Sundararaj Govindasamy
  • 7,142
  • 5
  • 41
  • 67
Srinivasan.S
  • 2,755
  • 1
  • 21
  • 14
7

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]
Brad Parks
  • 54,283
  • 54
  • 221
  • 287
5

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());
akhil_mittal
  • 18,855
  • 7
  • 83
  • 82
  • Does anyone know how can i convert this String to comma seperated list --String s = "2017-07-12 23:40:00.0,153.76,16.140,60.00,,56.00,"; List splittedString = new ArrayList(Arrays.asList(s.split("\\s*,\\s*"))); – Sunny Jun 02 '18 at 17:43
  • 1
    This is a new question, do not ask it as a comment. Feel free to create a new question. – George Siggouroglou Jun 04 '18 at 10:01
4

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*"));
 ...
Filippo Lauria
  • 1,846
  • 12
  • 19
  • 1
    You avoided the intermediary Arrays.asList. Unfortunately we still have a copy from array elements into the collection. Nice alternative to remember. – YoYo Aug 29 '18 at 15:02
2

In groovy, you can use tokenize(Character Token) method:

list = str.tokenize(',')
sivareddy963
  • 133
  • 11
2

Same result you can achieve using the Splitter class.

var list = Splitter.on(",").splitToList(YourStringVariable)

(written in kotlin)

chair_person
  • 11
  • 2
  • 4
anoopbryan2
  • 751
  • 9
  • 17
2

You can first split them using String.split(","), and then convert the returned String array to an ArrayList using Arrays.asList(array)

Saket
  • 42,173
  • 11
  • 56
  • 76
1
List commaseperated = new ArrayList();
String mylist = "item1 , item2 , item3";
mylist = Arrays.asList(myStr.trim().split(" , "));

// enter code here
PNDA
  • 776
  • 14
  • 39
1

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();
Jan Stanicek
  • 899
  • 1
  • 9
  • 27
1
List<String> items = Arrays.asList(s.split("[,\\s]+"));
Tunaki
  • 116,530
  • 39
  • 281
  • 370
Nenad Bulatovic
  • 6,570
  • 13
  • 70
  • 104
1

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(", ")
Vijendra patidar
  • 1,075
  • 1
  • 8
  • 22
1

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"]).

Julien Kronegg
  • 4,282
  • 42
  • 53
0

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);
Dulith De Costa
  • 8,429
  • 1
  • 53
  • 43
-1

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);
Farzan Skt
  • 783
  • 7
  • 7
-2

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());
Ajay Kumar
  • 3,408
  • 30
  • 35
-5
ArrayList<HashMap<String, String>> mListmain = new ArrayList<HashMap<String, String>>(); 
String marray[]= mListmain.split(",");
dur
  • 13,039
  • 20
  • 66
  • 96
jonsi
  • 3
  • 2
  • 6
    And where exactly is the `ArrayList`? Did you even read the question? – Debosmit Ray Mar 31 '16 at 06:44
  • @mapeters: There was a `ArrayList`. I rolled back the edits to the first revision (so you can see it) and improved the formatting of the first revision. – dur May 30 '17 at 12:32
  • Question is how to convert string to ArrayList, not how to convert ArrayList to Array. – comrade May 30 '17 at 18:50