在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允许将您的操作一个接一个地管道化,这是非常强大的。
为了,你懂的,完整。
其他回答
一个使用集合的例子。
import java.util.Collections;
...
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = new ArrayList<>();
Collections.addAll(items, commaSeparated.split("\\s*,\\s*"));
...
没有内置的方法,但你可以简单地使用split()方法。
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items =
new ArrayList<String>(Arrays.asList(commaSeparated.split(",")));
此方法将字符串转换为一个数组,并接受两个参数:要转换的字符串和分隔字符串中的值的字符。它转换它,然后返回转换后的数组。
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;
}
List<String> items = Arrays.asList(s.split("[,\\s]+"));
下面是另一个转换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));
}
打印你
——>字符串 ——> ——>逗号