How to convert a String into an ArrayList?

前端 未结 13 626
囚心锁ツ
囚心锁ツ 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条回答
  •  萌比男神i
    2020-11-28 04:44

    You could use:

    List tokens = Arrays.stream(s.split("\\s+")).collect(Collectors.toList());
    

    You should ask yourself if you really need the ArrayList in the first place. Very often, you're going to filter the list based on additional criteria, for which a Stream is perfect. You may want a set; you may want to filter them by means of another regular expression, etc. Java 8 provides this very useful extension, by the way, which will work on any CharSequence: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#splitAsStream-java.lang.CharSequence-. Since you don't need the array at all, avoid creating it thus:

    // This will presumably be a static final field somewhere.
    Pattern splitter = Pattern.compile("\\s+");
    // ...
    String untokenized = reader.readLine();
    Stream tokens = splitter.splitAsStream(untokenized);
    

提交回复
热议问题