Adding comma separated strings to an ArrayList and vice versa

前端 未结 11 1228
旧巷少年郎
旧巷少年郎 2021-01-01 05:18

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\".

<
11条回答
  •  天涯浪人
    2021-01-01 05:59

    This can help:

    for (String s : returnedItems.split(",")) {
        selItemArrayList.add(s.trim());
    }
    
    //Shorter and sweeter
    String [] strings = returnedItems.split(",");
    selItemArrayList = Arrays.asList(strings);
    
    //The reverse....
    
    StringBuilder sb = new StringBuilder();
    Iterator iter = selItemArrayList.iterator();
    while (iter.hasNext()) {
        if (sb.length() > 0) 
            sb.append(",");
        sb.append(iter.next());
    }
    
    returnedItems = sb.toString();
    

提交回复
热议问题