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

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

当前回答

没有内置的方法,但你可以简单地使用split()方法。

String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = 
new  ArrayList<String>(Arrays.asList(commaSeparated.split(",")));

其他回答

我通常使用预编译模式的列表。而且这也更通用一些,因为它可以考虑一些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();

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

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

Java 9引入了List.of():

String commaSeparated = "item1 , item2 , item3";
List<String> items = List.of(commaSeparated.split(" , "));

转换逗号分隔的字符串到列表

List<String> items = Arrays.asList(str.split("\\s*,\\s*"));

上面的代码在分隔符上分割字符串,分隔符定义为:零个或多个空格、一个文字逗号、零个或多个空格,这些空格将把单词放入列表中,并折叠单词和逗号之间的任何空格。


请注意,这只是返回一个数组的包装器:例如,你不能从结果列表中。remove()。对于实际的数组列表,必须进一步使用new ArrayList<String>。

List<String> items = Arrays.asList(s.split("[,\\s]+"));