在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是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 <String>,而不是ArrayList<String>。List的通用接口看起来仍然与ArrayList实现非常相似。
就其本身而言,这些代码示例似乎并没有增加很多内容(除了更多的输入),但是如果您打算做更多的事情,比如下面这个关于将String转换为List of long的示例,流式API允许将您的操作一个接一个地管道化,这是非常强大的。
为了,你懂的,完整。
其他回答
在java中,可以这样做
String catalogue_id = "A, B, C";
List<String> catalogueIdList = Arrays.asList(catalogue_id.split(", [ ]*"));
ArrayList<HashMap<String, String>> mListmain = new ArrayList<HashMap<String, String>>();
String marray[]= mListmain.split(",");
如果一个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 <String>,而不是ArrayList<String>。List的通用接口看起来仍然与ArrayList实现非常相似。
就其本身而言,这些代码示例似乎并没有增加很多内容(除了更多的输入),但是如果您打算做更多的事情,比如下面这个关于将String转换为List of long的示例,流式API允许将您的操作一个接一个地管道化,这是非常强大的。
为了,你懂的,完整。
你可以这样做。
这样就去掉了空白和用逗号分隔的地方,你不需要担心空白。
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);
我通常使用预编译模式的列表。而且这也更通用一些,因为它可以考虑一些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();