Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

How to get list of words from a list of lines in java?

If I have two lines, how can I split them into a list of two lists of words? I tried the following code:

ArrayList<String> lines = [Hello World, Welcome to StackOverFlow];
List<String> words;
List<List<String>> listOfWords;
for (int i = 0; i < lines.size(); i++) {
            words = Arrays.asList(lines.get(i).split(" "));
            listOfWords = Arrays.asList(words);
        }
System.out.println(listOfWords);

The output of the above code is

[[welcome, to, StackOverFlow]]

Can someone please help me to get the output as follows?

[[Hello, World], [Welcome, to, StackOverFlow]]

question from:https://stackoverflow.com/questions/65866421/how-to-get-list-of-words-from-a-list-of-lines-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

On every iteration of your for loop you are overwriting listOfWords by wrapping your latest words array in a new list. So effectively you will always just have your most recent line's list of words as the only item listOfWords.

To fix this modify following below the body of your for statement similar to the following:

  public static void main(String[] args) {
      String[] lines = {"Hello World", "Welcome to StackOverFlow"};
      List<String> words;
      List<List<String>> listOfWords = new ArrayList<List<String>>(); // Must be instantiated or you will get NullPointerException

      for (int i = 0; i < lines.length; i++) {
          words = Arrays.asList(lines[i].split(" "));
          listOfWords.add(words); //Add to `listOfWords` instead of replace with a totally new one
      }

      System.out.println(listOfWords);
  }

Some of the syntax was not correct so I fixed it. In that process I converted lines into an Array. Tested and confirmed output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...