How to convert comma-separated String to List?

前端 未结 24 1970
你的背包
你的背包 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:35

    Arrays.asList returns a fixed-size List backed by the array. If you want a normal mutable java.util.ArrayList you need to do this:

    List list = new ArrayList(Arrays.asList(string.split(" , ")));
    

    Or, using Guava:

    List list = Lists.newArrayList(Splitter.on(" , ").split(string));
    

    Using a Splitter gives you more flexibility in how you split the string and gives you the ability to, for example, skip empty strings in the results and trim results. It also has less weird behavior than String.split as well as not requiring you to split by regex (that's just one option).

提交回复
热议问题