在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??
当前回答
虽然这个问题已经很老了,并且已经被回答了很多次,但没有一个答案能够处理以下所有情况:
->空字符串应该映射到空列表 " 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”)。
其他回答
两个步骤:
String [] = commaSeparated.split项目(“\ \ s * \ \ s *”); List<String> container = Arrays.asList(items);
在groovy中,你可以使用tokenize(Character Token)方法:
list = str.tokenize(',')
在Kotlin中,如果你的字符串列表像这样,你可以使用这行代码将字符串转换为数组列表
var str= "item1, item2, item3, item4"
var itemsList = str.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是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允许将您的操作一个接一个地管道化,这是非常强大的。
为了,你懂的,完整。