Adding comma separated strings to an ArrayList and vice versa

前端 未结 11 1233
旧巷少年郎
旧巷少年郎 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条回答
  •  Happy的楠姐
    2021-01-01 05:52

    String csv = "Apple, Google, Samsung";
    

    step one : converting comma separate String to array of String

    String[] elements = csv.split(",");
    

    step two : convert String array to list of String

     List fixedLenghtList = Arrays.asList(elements);
    

    step three : copy fixed list to an ArrayList ArrayList listOfString = new ArrayList(fixedLenghtList);

    System.out.println("list from comma separated String : " + listOfString);
    

    System.out.println("size of ArrayList : " + listOfString.size()); Output :

    list of comma separated String : [Apple, Google, Samsung]
    
    
    size of ArrayList : 3
    

提交回复
热议问题