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

发布于 2024-12-05 16:58:23 字数 220 浏览 1 评论 0原文

Java 中是否有任何内置方法允许我们将逗号分隔的字符串转换为某个容器(例如数组、列表或向量)?或者我需要为此编写自定义代码吗?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(28

两相知 2024-12-12 16:58:23

将逗号分隔的字符串转换为列表

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

上面的代码在定义为的分隔符上分割字符串:零个或多个空格、文字逗号、零个或多个空格,这将放置单词进入列表并折叠单词和逗号之间的所有空格。


请注意,这只是返回一个数组的包装器:您不能,例如从生成的 List.remove()代码>.对于实际的ArrayList,您必须进一步使用new ArrayList

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

春夜浅 2024-12-12 16:58:23

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

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

或者,使用Guava

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

使用 Splitter 可以让您更灵活地拆分字符串,并能够跳过结果中的空字符串并修剪结果。它的奇怪行为也比 String.split 少,并且不需要您通过正则表达式进行拆分(这只是一种选择)。

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

孤城病女 2024-12-12 16:58:23

两步:

  1. String [] items = commaSeparated.split("\\s*,\\s*");
  2. List;容器 = Arrays.asList(items);

Two steps:

  1. String [] items = commaSeparated.split("\\s*,\\s*");
  2. List<String> container = Arrays.asList(items);
沉鱼一梦 2024-12-12 16:58:23
List<String> items= Stream.of(commaSeparated.split(","))
     .map(String::trim)
     .collect(Collectors.toList());
List<String> items= Stream.of(commaSeparated.split(","))
     .map(String::trim)
     .collect(Collectors.toList());
抱着落日 2024-12-12 16:58:23

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

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

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

如果按照 OP 的标题将结果存储为 ArrayList 很重要,您可以使用不同的 Collector 方法:

ArrayList<String> list = 
  Stream.of("a,b,c".split(","))
  .collect(Collectors.toCollection(ArrayList<String>::new));

或者使用 RegEx 解析 api:

ArrayList<String> list = 
  Pattern.compile(",")
  .splitAsStream("a,b,c")
  .collect(Collectors.toCollection(ArrayList<String>::new));

请注意,您仍然可以考虑将 list 变量保留为 List 类型,而不是 ArrayListList 的通用接口看起来仍然与 ArrayList 实现非常相似。

就其本身而言,这些代码示例似乎并没有添加很多内容(除了更多的输入),但如果您打算做更多,例如这个关于将字符串转换为长整型列表的答案 举例说明,流 API 非常强大,允许一个接一个地对您的操作进行管道化。

你知道,为了完整性。

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.

雨巷深深 2024-12-12 16:58:23

这是另一种将 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));
}

打印你

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

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

橘虞初梦 2024-12-12 16:58:23
List<String> items = Arrays.asList(commaSeparated.split(","));

那应该对你有用。

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

That should work for you.

兮颜 2024-12-12 16:58:23

没有内置方法,但您可以简单地使用 split() 方法。

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

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(",")));
天暗了我发光 2024-12-12 16:58:23

您可以组合 asList 和 split

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

you can combine asList and split

Arrays.asList(CommaSeparated.split("\\s*,\\s*"))
雨轻弹 2024-12-12 16:58:23

这段代码会有所帮助,

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

This code will help,

String myStr = "item1,item2,item3";
List myList = Arrays.asList(myStr.split(","));
与酒说心事 2024-12-12 16:58:23

您可以使用 Guava 拆分字符串,并将其转换为 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);

输出以下内容:

[item1, item2, item3]
[item1, item2, item3, another item]

您还可以在没有 Guava 的情况下使用以下方法:

  public static List<String> getStringAsList(String input) {
    if (input == null || input.trim().length() == 0) {
      return Collections.emptyList();
    }

    final String separators = "[;:,-]";
    var result =
        Splitter.on(CharMatcher.anyOf(separators))
            .trimResults()
            .omitEmptyStrings()
            .splitToList(input);

    return result;
  }

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]

You could also use the following approach without Guava:

  public static List<String> getStringAsList(String input) {
    if (input == null || input.trim().length() == 0) {
      return Collections.emptyList();
    }

    final String separators = "[;:,-]";
    var result =
        Splitter.on(CharMatcher.anyOf(separators))
            .trimResults()
            .omitEmptyStrings()
            .splitToList(input);

    return result;
  }
℉絮湮 2024-12-12 16:58:23

Java 9 引入了 List.of():

String commaSeparated = "item1 , item2 , item3";
List<String> items = List.of(commaSeparated.split(" , "));

Java 9 introduced List.of():

String commaSeparated = "item1 , item2 , item3";
List<String> items = List.of(commaSeparated.split(" , "));
迟月 2024-12-12 16:58:23

有很多方法可以使用 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());

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

在groovy中,您可以使用 tokenize(Character Token) 方法:

list = str.tokenize(',')

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

list = str.tokenize(',')
孤独岁月 2024-12-12 16:58:23

使用集合的示例。

import java.util.Collections;
 ...
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = new ArrayList<>();
Collections.addAll(items, commaSeparated.split("\\s*,\\s*"));
 ...

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*"));
 ...
阳光下慵懒的猫 2024-12-12 16:58:23

您可以先使用 String.split(",") 拆分它们,然后使用 将返回的 String array 转换为 ArrayList Arrays.asList(数组)

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

七七 2024-12-12 16:58:23

使用 Splitter 类可以获得相同的结果。

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

(用科特林编写)

Same result you can achieve using the Splitter class.

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

(written in kotlin)

她如夕阳 2024-12-12 16:58:23

虽然这个问题很旧并且已被多次回答,但没有一个答案能够管理以下所有情况:

  • "" ->空字符串应映射到空列表
  • " a, b , c " ->所有元素都应该被修剪,包括第一个和最后一个元素
  • ",," ->应该删除空元素

因此,我使用以下代码(使用 org.apache.commons.lang3.StringUtils,例如 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());

使用简单的分割表达式有一个优点:不使用正则表达式,所以性能大概是更高。 commons-lang3 库是轻量级且非常常见的。

请注意,该实现假设您没有包含逗号的列表元素(即 "a, 'b,c', d" 将被解析为 ["a", "'b ", "c'", "d"],而不是 ["a", "b,c", "d"])。

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

↙温凉少女 2024-12-12 16:58:23

在java中,可以这样完成

String catalogue_id = "A, B, C";
List<String> catalogueIdList = Arrays.asList(catalogue_id.split(", [ ]*"));

In java, It can be done like this

String catalogue_id = "A, B, C";
List<String> catalogueIdList = Arrays.asList(catalogue_id.split(", [ ]*"));
寒江雪… 2024-12-12 16:58:23
List commaseperated = new ArrayList();
String mylist = "item1 , item2 , item3";
mylist = Arrays.asList(myStr.trim().split(" , "));

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

// enter code here
段念尘 2024-12-12 16:58:23

我通常使用列表的预编译模式。而且这也稍微更通用,因为它可以考虑一些 listToString 表达式后面的括号。

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

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();
嗫嚅 2024-12-12 16:58:23
List<String> items = Arrays.asList(s.split("[,\\s]+"));
List<String> items = Arrays.asList(s.split("[,\\s]+"));
请爱~陌生人 2024-12-12 16:58:23

在 Kotlin 中,如果您的字符串列表是这样的,并且您可以使用这行代码将字符串转换为 ArrayList

var str= "item1, item2, item3, item4"
var itemsList = str.split(", ")

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(", ")
幸福不弃 2024-12-12 16:58:23

您可以按如下方式进行操作。

这会删除空格并用逗号分隔,您无需担心空格。

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

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);
失眠症患者 2024-12-12 16:58:23

此方法会将字符串转换为数组,并采用两个参数:

  • 要转换的字符串以及
  • 分隔字符串中的值的字符。

然后它返回转换后的数组。

private String[] convertStringToArray(String stringIn, String separators){
    
    // separate string into list depending on separators
    List<String> tempList = Arrays.asList(stringIn.split(separators));
    
    // create a new pre-populated array based on the size of the list
    String[] itemsArray = new String[tempList.size()];
    
    // convert the list to an array
    itemsArray = tempList.toArray(itemsArray);
    
    return itemsArray;
}

This method will convert your string to an array, taking two parameters:

  • the string you want converted, and
  • the characters that will separate the values in the string.

It then returns the converted array.

private String[] convertStringToArray(String stringIn, String separators){
    
    // separate string into list depending on separators
    List<String> tempList = Arrays.asList(stringIn.split(separators));
    
    // create a new pre-populated array based on the size of the list
    String[] itemsArray = new String[tempList.size()];
    
    // convert the list to an array
    itemsArray = tempList.toArray(itemsArray);
    
    return itemsArray;
}
少年亿悲伤 2024-12-12 16:58:23

以下是利用 Java 8 流的代码的另外两个扩展版本:

List<String> stringList1 = 
    Arrays.stream(commaSeparated.split(","))
      .map(String::trim)
      .collect(Collectors.toList());

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

Here are two more extended versions of the code that utilize Java 8 streams:

List<String> stringList1 = 
    Arrays.stream(commaSeparated.split(","))
      .map(String::trim)
      .collect(Collectors.toList());

List<String> stringList2 = 
    Stream.of(commaSeparated.split(","))
      .map(String::trim)
      .collect(Collectors.toList());
清泪尽 2024-12-12 16:58:23

将 Collection 转换为字符串,以 Java 8 中的逗号分隔

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

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

输出为 :-
'A'、'B'、'C'、'D'

以及在 Java 8 中将字符串数组转换为列表

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

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());
花海 2024-12-12 16:58:23
ArrayList<HashMap<String, String>> mListmain = new ArrayList<HashMap<String, String>>(); 
String marray[]= mListmain.split(",");
ArrayList<HashMap<String, String>> mListmain = new ArrayList<HashMap<String, String>>(); 
String marray[]= mListmain.split(",");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文