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

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

当前回答

你可以先使用String.split(",")分割它们,然后使用Arrays.asList(array)将返回的String数组转换为数组列表

其他回答

你可以这样做。

这样就去掉了空白和用逗号分隔的地方,你不需要担心空白。

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

下面是另一个转换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));
}

打印你

——>字符串 ——> ——>逗号

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

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 8流的另外两个扩展版本如下所示

List<String> stringList1 = Arrays.stream(commaSeparated.split(",")).map(String::trim).collect(Collectors.toList());
List<String> stringList2 = Stream.of(commaSeparated.split(",")).map(String::trim).collect(Collectors.toList());
List<String> items= Stream.of(commaSeparated.split(","))
     .map(String::trim)
     .collect(Collectors.toList());