Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding comma separated strings to an ArrayList and vice versa

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.

like image 528
user676567 Avatar asked Nov 28 '22 01:11

user676567


2 Answers

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();
like image 176
dogbane Avatar answered Dec 04 '22 22:12

dogbane


One-liners are always popular:

Collections.addAll(arrayList, input.split(","));
like image 36
Peter Knego Avatar answered Dec 04 '22 20:12

Peter Knego