且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

添加逗号分隔字符串到一个ArrayList,反之亦然

更新时间:2023-11-05 21:54:46

 字符串returnedItems =A,B,C;
清单<串GT; sellItems = Arrays.asList(returnedItems.split(,));

现在遍历列表,每个项目追加到StringBuilder的:

  StringBuilder的SB =新的StringBuilder();
对于(字符串项:sellItems){
    如果(sb.length()大于0){
        sb.append(,);
    }
    sb.append(项目);
}
字符串结果= sb.toString();

How to add a comma separated string to an ArrayList? My string "returnedItems" could hold 1 or 20 items which I'd like to add to my ArrayList "selItemArrayList".

After the ArrayList has been populated, I'd like to later iterate through it and format the items into a comma separated string with no spaces between the items.

String returnedItems = "a,b,c";
List<String> sellItems = Arrays.asList(returnedItems.split(","));

Now iterate over the list and append each item to a StringBuilder:

StringBuilder sb = new StringBuilder();
for(String item: sellItems){
    if(sb.length() > 0){
        sb.append(',');
    }
    sb.append(item);
}
String result = sb.toString();