How to convert a String into an ArrayList?

前端 未结 13 630
囚心锁ツ
囚心锁ツ 2020-11-28 04:32

In my String, I can have an arbitrary number of words which are comma separated. I wanted each word added into an ArrayList. E.g.:

String s = \"a,b,c,d,e,...         


        
13条回答
  •  情歌与酒
    2020-11-28 05:03

    Try something like

    List myList = new ArrayList(Arrays.asList(s.split(",")));
    
    • Arrays.asList documentation
    • String.split documentation
    • ArrayList(Collection) constructor documentation

    Demo:

    String s = "lorem,ipsum,dolor,sit,amet";
    
    List myList = new ArrayList(Arrays.asList(s.split(",")));
    
    System.out.println(myList);  // prints [lorem, ipsum, dolor, sit, amet]
    

    This post has been rewritten as an article here.

提交回复
热议问题