How to convert comma-separated String to List?

前端 未结 24 1984
你的背包
你的背包 2020-11-22 16:58

Is there any built-in method in Java which allows us to convert comma separated String to some container (e.g array, List or Vector)? Or do I need to write custom code for t

24条回答
  •  清酒与你
    2020-11-22 17:34

    You can use Guava to split the string, and convert it into an ArrayList. This works with an empty string as well, and returns an empty list.

    import com.google.common.base.Splitter;
    import com.google.common.collect.Lists;
    
    String commaSeparated = "item1 , item2 , item3";
    
    // Split string into list, trimming each item and removing empty items
    ArrayList list = Lists.newArrayList(Splitter.on(',').trimResults().omitEmptyStrings().splitToList(commaSeparated));
    System.out.println(list);
    
    list.add("another item");
    System.out.println(list);
    

    outputs the following:

    [item1, item2, item3]
    [item1, item2, item3, another item]
    

提交回复
热议问题