Adding comma separated strings to an ArrayList and vice versa

前端 未结 11 1175
旧巷少年郎
旧巷少年郎 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:47

    split and asList do the trick:

    String [] strings = returnedItems.split(",");
    List<String> list = Arrays.asList(strings);
    
    0 讨论(0)
  • 2021-01-01 05:47

    If the strings themselves can have commas in them, things get more complicated. Rather than rolling your own, consider using one of the many open-source CSV parsers. While they are designed to read in files, at least OpenCSV will also parse an individual string you hand it.

    • Commons CSV
    • OpenCSV
    • Super CSV
    • OsterMiller CSV
    0 讨论(0)
  • 2021-01-01 05:47
    String list = "one, two, three, four";
    String[] items = list.split("\\p{Punct}");
    List<String> aList = Arrays.asList(items);
    System.out.println("aList = " + aList);
    StringBuilder formatted = new StringBuilder();
    
    for (int i = 0; i < items.length; i++)
    {
        formatted.append(items[i].trim());
        if (i < items.length - 1) formatted.append(',');
    }
    
    System.out.println("formatted = " + formatted.toString());
    
    0 讨论(0)
  • 2021-01-01 05:50

    Simple one-liner:

    selItemArrayList.addAll(Arrays.asList(returnedItems.split("\\s*,\\s*")));
    

    Of course it will be more complex if you have entries with commas in them.

    0 讨论(0)
  • 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<String> 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
    
    0 讨论(0)
  • 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<String> iter = selItemArrayList.iterator();
    while (iter.hasNext()) {
        if (sb.length() > 0) 
            sb.append(",");
        sb.append(iter.next());
    }
    
    returnedItems = sb.toString();
    
    0 讨论(0)
提交回复
热议问题