Shruti sharma
Shruti sharma

Reputation: 211

Not able to access individual element from sublist

I am a beginner in java. I want to read elements one by one in sublist.

public class ListFirst {
    
    public static void main(String[] args) {
        
        List<Integer>list1= Arrays.asList(10,20,30,40);
        List<Integer>list2=Arrays.asList(100,200,300,400);
        List<List<Integer>>bigList= new ArrayList<>();
       
         // I want to access an element of bigList one by one. how to do that?
        
    }

}

If there is no sublist I can print using for loop upto list.size() and list.get() to print but here element is list itself..so I dont know how to read. could you please help me with that.

Upvotes: 0

Views: 63

Answers (3)

wollsi
wollsi

Reputation: 58

I modified your code to achieve what you wanted to do:


public class ListFirst {
    
    public static void main(String[] args) {
        
        List<Integer>list1= Arrays.asList(10,20,30,40);
        List<Integer>list2=Arrays.asList(100,200,300,400);

        List<List<Integer>>bigList= new ArrayList<>();

        bigList.add(list1);
        bigList.add(list2);
       
        for (List<Integer> list : bigList) {
            for (Integer i : list) {
                System.out.print(i.intValue() + " ");
            }
        }
        
    }

}

An alternative would be to not use nested List for storing your Integers:

public static void main(String[] args) {
    
    List<Integer>list1= Arrays.asList(10,20,30,40);
    List<Integer>list2=Arrays.asList(100,200,300,400);

    // bigList is a list of Integers not list of lists
    List<Integer>bigList= new ArrayList<>();

    bigList.addAll(list1); // add all elements from list1
    bigList.addAll(list2); // add all elements from list2
    
    for (Integer i : bigList) {
        System.out.print(i.intValue() + " ");
    }
}

Upvotes: 3

Most Noble Rabbit
Most Noble Rabbit

Reputation: 2776

You can do the following:

bigList.stream()
    .flatMap(Collection::stream)
    .forEach(x -> System.out.println(x));

Output:

10
20
30
40
100
200
300
400

Upvotes: 0

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

Assuming that the lists have bee added to bigList, you can iterate it using the for-each loop as shown below:

bigList.add(list1);
bigList.add(list2);

for (List<Integer> list : bigList) {
    System.out.println(list);
}

DEMO

Using the traditional loop, you can print bigList as shown below:

for (int i = 0; i < bigList.size(); i++) {
    System.out.println(bigList.get(i));
}

Upvotes: 1

Related Questions