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

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

当前回答

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

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

(用kotlin写)

其他回答

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

list = str.tokenize(',')
List<String> items= Stream.of(commaSeparated.split(","))
     .map(String::trim)
     .collect(Collectors.toList());

如果一个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 [] = commaSeparated.split项目(“\ \ s * \ \ s *”); List<String> container = Arrays.asList(items);

此方法将字符串转换为一个数组,并接受两个参数:要转换的字符串和分隔字符串中的值的字符。它转换它,然后返回转换后的数组。

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