如何将逗号分隔的字符串转换为ArrayList?

时间:2021-01-18 00:18:46

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?

Java中是否有内置的方法可以让我们将逗号分隔的字符串转换为某个容器(e)。g数组,列表还是向量)?或者我需要为此编写自定义代码吗?

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

22 个解决方案

#1


793  

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.

上面的代码分割了分隔符上的字符串,定义为:0或更多的空格、一个文字逗号、0或更多的空格,这些空格将把单词放入列表中,并将单词和逗号之间的任何空格折叠起来。


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

请注意,这只返回数组的包装器:例如,不能从结果列表中删除()。对于实际的ArrayList,您必须进一步使用新的ArrayList

#2


156  

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:

数组。asList返回由数组支持的固定大小的列表。如果您想要一个普通的可变java.util。ArrayList你需要这样做:

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

使用Splitter可以使您在分割字符串时更加灵活,并使您能够在结果中跳过空字符串,并修剪结果。它也没有字符串那么奇怪。分割以及不需要通过regex进行分割(这只是一个选项)。

#3


56  

Two steps:

两个步骤:

  1. String [] items = commaSeparated.split(",");
  2. String [] items = commaseparate .split(",");
  3. List<String> container = Arrays.asList(items);
  4. 容器列表 <字符串> = arrays . aslist(项目);

#4


20  

Here is another one for converting CSV to ArrayList:

下面是另一个将CSV转换为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

- - >字符串- - > - - >逗号

#5


14  

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

这里没有内置的方法,但是您可以使用split()方法。

String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = 
new  ArrayList<String>(Arrays.asList(commaSeparated.split(",")));

#6


9  

List<String> items = Arrays.asList(commaSeparated.split(","));

That should work for you.

这对你应该有效。

#7


9  

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 you alternatives using Java 8 Streams, that will give you more benefit if it is part of a pipeline for further processing.

如果列表是最终目标,如OP所述,那么已经被接受的答案仍然是最短和最好的。但是,我想为您提供使用Java 8流的替代方案,如果它是用于进一步处理的管道的一部分,那么它将给您带来更多的好处。

By wrapping the result of the .split function (a native array) into a stream and then converting to a list.

通过将.split函数(本机数组)的结果封装到流中,然后转换为列表。

List<String> list =
  Stream.of("a,b,c".split(","))
  .collect(Collectors.toList());

Or by using the RegEx parsing api:

或使用RegEx解析api:

List<String> list = 
  Pattern.compile(",")
  .splitAsStream("a,b,c")
  .collect(Collectors.toList());

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.

本身,这些代码示例似乎并不添加很多(除了更多的输入),但如果你计划做更多的事情,这样的回答将一个字符串转换为一个多头列表了,流API非常强大,允许管道操作一个接一个。

For the sake of, you know, completeness.

为了,你知道的,完整性。

#8


9  

List<String> items= Stream.of(commaSeparated.split(","))
     .map(String::trim)
     .collect(toList());

#9


8  

you can combine asList and split

您可以组合asList和split

Arrays.asList(CommaSeparated.split("\\s*,\\s*"))

#10


3  

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*"));
 ...

#11


3  

This below code may help you,

下面的代码可以帮助您,

List myList = new ArrayList();
String myStr = "item1 , item2 , item3";
myList = Arrays.asList(myStr.split(" , "));

#12


3  

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.

您可以使用番石榴来分割字符串,并将其转换为ArrayList。这同样适用于一个空字符串,并返回一个空列表。

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]

#13


1  

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

首先可以使用String.split(",")对它们进行分割,然后使用Arrays.asList(数组)将返回的字符串数组转换为ArrayList

#14


1  

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

// enter code here

#15


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();

#16


0  

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

在groovy中,可以使用tokenize(字符标记)方法:

list = str.tokenize(',')

#17


0  

String -> Collection conversion: (String -> String[] -> Collection)

字符串->集合转换:(String -> String[] ->集合)

//         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[]转换:

String[] se = col.toArray(new String[col.size()]);

String -> String[] conversion:

- >字符串String[]转换:

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

And Collection -> Collection:

收集和收集- >:

List<String> list = new LinkedList<>(col);

#18


0  

List<String> items = Arrays.asList(s.split("[,\\s]+"));

#19


0  

There are many ways to solve this using streams in Java 8 but IMO the following one liners are straight forward:

使用Java 8中的流解决这个问题的方法有很多,但是在我看来,下面的一行是直接向前的:

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());

#20


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

#21


-1  

convert Collection into string as comma seperated in Java 8

在Java 8中,将集合转换成逗号分隔的字符串

listOfString object contains ["A","B","C" ,"D"] elements-

listOfString对象包含["A"、"B"、"C"、"D"]元素-

listOfString.stream().map(ele->"'"+ele+"'").collect(Collectors.joining(","))

Output is :- 'A','B','C','D'

输出:- A,B,C,D的

And Convert Strings Array to List in Java 8

并将字符串数组转换为Java 8中的列表

    String string[] ={"A","B","C","D"};
    List<String> listOfString = Stream.of(string).collect(Collectors.toList());

#22


-3  

ArrayList<HashMap<String, String>> mListmain = new ArrayList<HashMap<String, String>>(); 
String marray[]= mListmain.split(",");

#1


793  

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.

上面的代码分割了分隔符上的字符串,定义为:0或更多的空格、一个文字逗号、0或更多的空格,这些空格将把单词放入列表中,并将单词和逗号之间的任何空格折叠起来。


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

请注意,这只返回数组的包装器:例如,不能从结果列表中删除()。对于实际的ArrayList,您必须进一步使用新的ArrayList

#2


156  

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:

数组。asList返回由数组支持的固定大小的列表。如果您想要一个普通的可变java.util。ArrayList你需要这样做:

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

使用Splitter可以使您在分割字符串时更加灵活,并使您能够在结果中跳过空字符串,并修剪结果。它也没有字符串那么奇怪。分割以及不需要通过regex进行分割(这只是一个选项)。

#3


56  

Two steps:

两个步骤:

  1. String [] items = commaSeparated.split(",");
  2. String [] items = commaseparate .split(",");
  3. List<String> container = Arrays.asList(items);
  4. 容器列表 <字符串> = arrays . aslist(项目);

#4


20  

Here is another one for converting CSV to ArrayList:

下面是另一个将CSV转换为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

- - >字符串- - > - - >逗号

#5


14  

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

这里没有内置的方法,但是您可以使用split()方法。

String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = 
new  ArrayList<String>(Arrays.asList(commaSeparated.split(",")));

#6


9  

List<String> items = Arrays.asList(commaSeparated.split(","));

That should work for you.

这对你应该有效。

#7


9  

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 you alternatives using Java 8 Streams, that will give you more benefit if it is part of a pipeline for further processing.

如果列表是最终目标,如OP所述,那么已经被接受的答案仍然是最短和最好的。但是,我想为您提供使用Java 8流的替代方案,如果它是用于进一步处理的管道的一部分,那么它将给您带来更多的好处。

By wrapping the result of the .split function (a native array) into a stream and then converting to a list.

通过将.split函数(本机数组)的结果封装到流中,然后转换为列表。

List<String> list =
  Stream.of("a,b,c".split(","))
  .collect(Collectors.toList());

Or by using the RegEx parsing api:

或使用RegEx解析api:

List<String> list = 
  Pattern.compile(",")
  .splitAsStream("a,b,c")
  .collect(Collectors.toList());

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.

本身,这些代码示例似乎并不添加很多(除了更多的输入),但如果你计划做更多的事情,这样的回答将一个字符串转换为一个多头列表了,流API非常强大,允许管道操作一个接一个。

For the sake of, you know, completeness.

为了,你知道的,完整性。

#8


9  

List<String> items= Stream.of(commaSeparated.split(","))
     .map(String::trim)
     .collect(toList());

#9


8  

you can combine asList and split

您可以组合asList和split

Arrays.asList(CommaSeparated.split("\\s*,\\s*"))

#10


3  

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*"));
 ...

#11


3  

This below code may help you,

下面的代码可以帮助您,

List myList = new ArrayList();
String myStr = "item1 , item2 , item3";
myList = Arrays.asList(myStr.split(" , "));

#12


3  

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.

您可以使用番石榴来分割字符串,并将其转换为ArrayList。这同样适用于一个空字符串,并返回一个空列表。

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]

#13


1  

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

首先可以使用String.split(",")对它们进行分割,然后使用Arrays.asList(数组)将返回的字符串数组转换为ArrayList

#14


1  

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

// enter code here

#15


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();

#16


0  

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

在groovy中,可以使用tokenize(字符标记)方法:

list = str.tokenize(',')

#17


0  

String -> Collection conversion: (String -> String[] -> Collection)

字符串->集合转换:(String -> String[] ->集合)

//         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[]转换:

String[] se = col.toArray(new String[col.size()]);

String -> String[] conversion:

- >字符串String[]转换:

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

And Collection -> Collection:

收集和收集- >:

List<String> list = new LinkedList<>(col);

#18


0  

List<String> items = Arrays.asList(s.split("[,\\s]+"));

#19


0  

There are many ways to solve this using streams in Java 8 but IMO the following one liners are straight forward:

使用Java 8中的流解决这个问题的方法有很多,但是在我看来,下面的一行是直接向前的:

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());

#20


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

#21


-1  

convert Collection into string as comma seperated in Java 8

在Java 8中,将集合转换成逗号分隔的字符串

listOfString object contains ["A","B","C" ,"D"] elements-

listOfString对象包含["A"、"B"、"C"、"D"]元素-

listOfString.stream().map(ele->"'"+ele+"'").collect(Collectors.joining(","))

Output is :- 'A','B','C','D'

输出:- A,B,C,D的

And Convert Strings Array to List in Java 8

并将字符串数组转换为Java 8中的列表

    String string[] ={"A","B","C","D"};
    List<String> listOfString = Stream.of(string).collect(Collectors.toList());

#22


-3  

ArrayList<HashMap<String, String>> mListmain = new ArrayList<HashMap<String, String>>(); 
String marray[]= mListmain.split(",");