将逗号分隔的字符串添加到ArrayList,反之亦然 [英] Adding comma separated strings to an ArrayList and vice versa
本文介绍了将逗号分隔的字符串添加到ArrayList,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将逗号分隔的字符串添加到ArrayList?我的字符串returnedItems可能包含1或20个项目,我想将其添加到我的ArrayListselItemArrayList。
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".
填充ArrayList后,我会喜欢稍后迭代它并将项目格式化为逗号分隔的字符串,项目之间没有空格。
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(","));
现在迭代列表并将每个项目附加到StringBuilder:
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();
这篇关于将逗号分隔的字符串添加到ArrayList,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文