在Java中是否有任何内置的方法可以将逗号分隔的字符串转换为某个容器(例如数组、列表或向量)?还是我需要编写自定义代码来实现?
String commaSeparated = "item1 , item2 , item3";
List<String> items = //method that converts above string into list??
在Java中是否有任何内置的方法可以将逗号分隔的字符串转换为某个容器(例如数组、列表或向量)?还是我需要编写自定义代码来实现?
String commaSeparated = "item1 , item2 , item3";
List<String> items = //method that converts above string into list??
将逗号分隔的字符串转换为列表
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
上面的代码使用的分隔符定义为:零个或多个空格、一个逗号、零个或多个空格
,这会将单词放入列表中并折叠单词和逗号之间的任何空格。List
中使用.remove()
。要获得实际的ArrayList
,您必须进一步使用new ArrayList<String>
。\s
匹配任何空白字符,*
表示该匹配零次或多次。因此 \s*
表示“匹配任意空白字符零次或多次”。我们在逗号之前和之后查找此模式。因此,该拆分将适用于诸如 "item1 , item2 , item3"
或 "item1,item2 ,item3"
等字符串。在Java中,您需要在字符串中转义反斜杠,因此您会得到 \\s*
。 - andrewrjones"[\\s,]+"
将会在逗号分隔的标记内部空格上进行拆分,即使没有逗号存在,它也会把两个空格都视为定界符。"\\s*(,\\s*)+"
仅会修剪逗号分隔的标记周围的空格,并忽略任何只包含空格或为空的字符串。 - theferrit32Arrays.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
提供了一个原生数组的包装器(避免了元素复制),但 new ArrayList(...)
将会进行逐个元素的复制。我们应该优先选择一种方法,允许将解析后的元素直接添加到目标集合中。 - YoYo两个步骤:
String [] items = commaSeparated.split("\\s*,\\s*");
将逗号分隔的字符串转换为字符串数组。List<String> container = Arrays.asList(items);
将字符串数组转换为列表。split
方法的参数被解释为正则表达式。 - MadbreaksList<String> items= Stream.of(commaSeparated.split(","))
.map(String::trim)
.collect(Collectors.toList());
collect(toList())
改为 collect(Collectors.toList())
后仍可正常工作。 - Sundararaj Govindasamycollect(toList())
是使用静态导入 Collectors.toList()
来简洁和流畅地编写代码 :) - ManuList
是OP所述的终极目标,那么已经接受的答案仍然是最短和最好的。但是我想提供使用Java 8 Streams的替代方法,如果它是进一步处理的管道的一部分,那么这将给您带来更多的好处。List<String> list =
Stream.of("a,b,c".split(","))
.collect(Collectors.toList());
ArrayList
,您可以使用不同的Collector
方法:ArrayList<String> list =
Stream.of("a,b,c".split(","))
.collect(Collectors.toCollection(ArrayList<String>::new));
或者使用正则表达式解析 API:
ArrayList<String> list =
Pattern.compile(",")
.splitAsStream("a,b,c")
.collect(Collectors.toCollection(ArrayList<String>::new));
list
变量保留为List<String>
类型,而不是ArrayList<String>
。泛型接口List
看起来与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));
}
打印你
-->字符串
-->带有
-->逗号
List<String> items = Arrays.asList(commaSeparated.split(","));
那应该对你有用。
虽然没有内置的方法可以做到这一点,但是您可以很简单地使用split()方法。
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items =
new ArrayList<String>(Arrays.asList(commaSeparated.split(",")));
你可以将asList和split组合使用
Arrays.asList(CommaSeparated.split("\\s*,\\s*"))
这段代码将会有所帮助,
String myStr = "item1,item2,item3";
List myList = Arrays.asList(myStr.split(","));
groovy
中能够工作,但是没有 :( - mdabdullah