Ally
Ally

Reputation: 21

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;

Upvotes: 1

Views: 2623

Answers (3)

Ibrokhim Kholmatov
Ibrokhim Kholmatov

Reputation: 1089

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();
} 

Upvotes: 2

ajc
ajc

Reputation: 1725

Or something like this as well...

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

Upvotes: 0

RAZ_Muh_Taz
RAZ_Muh_Taz

Reputation: 4089

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("");
}

Upvotes: 7

Related Questions