简体   繁体   中英

How to iterate through an arraylist of an arraylist of strings?

I'm creating a program that allows users to interact with a file thats input. One of the options is to display the file. Below, I store the file into an arraylist first by creating arraylists consisting of lines, and then an inner arraylist separated of strings, separated by spaces.

Scanner sc = new Scanner(fileName);

    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        String[] words = {};
        words = line.split(" ");
        ArrayList<String> lineArray = new ArrayList<String>();
        for (int i = 0; i < words.length; i++) {
            lineArray.add(words[i]);
        }
        fileByLine.add(lineArray);
    }
    sc.close();

I'm trying to print the contents of the arraylist, called fileByLine, as they appear in the file, but I'm not sure how to. Any suggestion?

case '1':
for(int i = 0; i < fileByLine.size(); i++){
for(int j = 0; j < fileByLine.[i].size(); j++){
System.out.print(fileByLine[i][j]);
  } System.out.println("");
} break;

You are using bracket notation which is for arrays, you need to use get() for arraylists

for(int i = 0; i < fileByLine.size(); i++){
    for(int j = 0; j < fileByLine.get(i).size(); j++){
        System.out.print(fileByLine.get(i).get(j));
    }
    System.out.println("");
}

Since your container consist of String type you can just print it as follow:

System.out.println(fileByLine);

No need to loop through your collection. For example, let's say you have following list:

List<String> oneList = new ArrayList<>(Arrays.asList("1 2 3 4 5 6 7".split(" ")));

and you want to add it into another list:

List<List<String>> anotherList = new ArrayList<>();
anotherList.add(oneList);

After adding you would like to print it and here is how it looks:

System.out.println(anotherList);

Output: [[1, 2, 3, 4, 5, 6, 7]]

It prints because of String type if you keep any other custom type in your container and try to print it that will not work until you override toString() method.

If you need to iterate over two nested lists you can use this approach too:

Iterator<List<String>> outerIterator = anotherList.listIterator();

while (outerIterator.hasNext()) {
    Iterator<String> innerIterator = outerIterator.next().listIterator();

    while (innerIterator.hasNext()) {
        String item = innerIterator.next();
        System.out.print(item + " ");
    }

    System.out.println();
} 

Or something like this as well...

     for (List list : fileByLine) {
        for (Object line : list) {
            System.out.print(line);
        }
        System.out.println("");
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM