如何将逗号分隔的字符串转换为列表?

653

在Java中是否有任何内置的方法可以将逗号分隔的字符串转换为某个容器(例如数组、列表或向量)?还是我需要编写自定义代码来实现?

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

如果您想解析CSV,请参见https://dev59.com/Y1HTa4cB1Zd3GeqPORBa。 - Raedwald
@Raedwald,但这不是OP所要求的。 - Crowie
3
假设您想要与问题标题中所述的 ArrayList 一样,那么只有 ColinD 的答案是正确的。ArrayList(可变)与 List 完全不同,后者可以仅仅是一个简单的固定列表。 - Fattie
@Fattie - 说得好,已经修复了 - https://dev59.com/Bms05IYBdhLWcg3wCNlG#34735419 - YoYo
1
Java 8 解决方案:https://dev59.com/Bms05IYBdhLWcg3wCNlG#46485179 - akhil_mittal
28个回答

1

在 Kotlin 中,如果您的字符串列表是这样的,您可以使用以下代码将其转换为 ArrayList

var str= "item1, item2, item3, item4"
var itemsList = str.split(", ")

1
List commaseperated = new ArrayList();
String mylist = "item1 , item2 , item3";
mylist = Arrays.asList(myStr.trim().split(" , "));

// enter code here

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

0
你可以按照以下方式进行操作。
这将删除空格并按逗号拆分,您无需担心空格。
    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);

0

这个方法将把你的字符串转换为数组,需要两个参数:

  • 你想要转换的字符串,以及
  • 在字符串中分隔值的字符。

然后它会返回转换后的数组。

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

-1

这里有两个更加扩展的代码版本,它们利用了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());

-2

Java 8中将集合转换为逗号分隔的字符串

listOfString对象包含["A","B","C","D"]元素 -

listOfString.stream().map(ele->"'"+ele+"'").collect(Collectors.joining(","))

输出为: 'A','B','C','D'

在Java 8中将字符串数组转换为列表

    String string[] ={"A","B","C","D"};
    List<String> listOfString = Stream.of(string).collect(Collectors.toList());

-5
ArrayList<HashMap<String, String>> mListmain = new ArrayList<HashMap<String, String>>(); 
String marray[]= mListmain.split(",");

6
ArrayList在哪里?你有认真阅读问题吗? - Debosmit Ray
@mapeters:有一个ArrayList。我将编辑回滚到第一个版本(这样您就可以看到它),并改善了第一个版本的格式。 - dur
问题是如何将字符串转换为ArrayList,而不是将ArrayList转换为数组。 - comrade

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接