Abeer
Abeer

Reputation: 83

get values in List of Lists Java

I have a List of List array

List <List<String>> fname;

System.out.println(fname.get(0).get(0));-->gives 1st file name

I want to retrieve each element in the array List without using two for loop (as a solution I thought of) because it will increase the complexity any help??

Upvotes: 1

Views: 7671

Answers (2)

phflack
phflack

Reputation: 2727

Note that while this is one loop, it is much easier to do it with nested for loops

List<List<String>> list;
int x = 0;
int y = 0;
while(x < list.size())
{
    if(y < list.get(x).size())
    {
        //do stuff with list.get(x).get(y)
        y++;
    }
    else
    {
        x++;
        y = 0;
    }
}

A much more preferred way to loop through all of the elements, and should be just as fast if not faster

List<List<String>> list;
for(List<String> l : list)
    for(String s : l)
        //do stuff with s

Upvotes: 2

Bon
Bon

Reputation: 3103

In Java 8, you can simply use one statement:

fname.forEach(sublist -> sublist.forEach(element -> System.out.println(element)));

Upvotes: 1

Related Questions