How to iterate over a 2D list (list of lists) in Java?


A data structure known as a 2D list or list of lists can be utilised for saving a collection of data in a two-dimensional format.

A row in the 2D list is represented by each inner list in this list of lists.

A 2D list could be utilised, for instance, to store the data for a chessboard, where every component in the list corresponds to a single square on the board.

Methods Used

A 2D list can be iterated in one of the two methods that follow −

  • Using Loops

  • Using iterator

Method 1: Employing Loops

There are two ways for you to traverse over a 2D list (a list of lists).

The first is the usage of a nested for-each loop. For this, we must first retrieve the 2D list that you would like to iterate. After this, you can effectively traverse through the entries of the list using two for-each loops.

In the first for-each loop, each row of the 2D list is considered a separate list. You may utilise the variable "list" to indicate each row of the 2D list −

Syntax

for (List<K> list : listOfLists) {
   // Perform operations on each row (list) here
}

When using the second for-each loop, you can access each item within each row individually. Here, the variable "item" represents each item −

Syntax

for (K item : list) {
   // Perform operations on each item here
}

By employing these nested for-each loops, you may effectively iterate over a 2D list and control its elements according to your necessities.

for()

The code demonstrates how to iterate over a 2D list (list of lists) in Java by using nested for-each loops. It prints the elements of each inner list in the desired format.

Algorithm

  • Step 1 − Import necessary libraries for the code.

  • Step 2 − Create the "iterateUsingForEach" function, which accepts a list of lists as an argument.

  • Step 3 − Print an opening bracket "[" to indicate the start of the list.

  • Step 4 − Traverse over each list in the input listOfLists.

  • Step 5 − For every list, print an opening bracket "[" to show the beginning of the inner list.

  • Step 6 − Iterate over each item within the current list.

  • Step 7 − Print each item. Add commas to separate them.

  • Step 8 − Print a closing bracket "]" to indicate the end of the inner list, and a comma and a space.

  • Step 9 − Print a closing bracket "]" to indicate the end of the outer list.

  • Step 10 − Exit the function.

  • Step 11 − In the main function −

    • Create an empty list called "listOfLists" to hold the lists of integers.

    • Create four separate lists and populate them with integers.

    • Add each of these individual lists to the "listOfLists".

  • Step 12 − Call the "iterateUsingForEach" function, passing within the "listOfLists" as an argument to print the lists in the desired format.

  • Step 13 − The method's output is the printed version of the "listOfLists.”

Example

import java.util.*;

public class List_of_list {

   public static <K> void iterateUsingForEach(List<List<K>> listOfLists) {

      System.out.println("[");

      for (List<K> list : listOfLists) {
         System.out.print(" [");

         for (K item : list) {
            System.out.print(" " + item + ", ");
         }
         System.out.println("], ");
      }
      System.out.println("]");
   }

   public static void main(String[] args) {

      // List of Lists
      ArrayList<List<Integer>> listOfLists = new ArrayList<List<Integer>>();

      List<Integer> list1 = new ArrayList<Integer>();
      list1.add(50);
      list1.add(100);
      listOfLists.add(list1);

      List<Integer> list2 = new ArrayList<Integer>();
      list2.add(2);
      listOfLists.add(list2);

      List<Integer> list3 = new ArrayList<Integer>();  // Corrected variable name
      list3.add(200);
      list3.add(300);
      list3.add(400);
      listOfLists.add(list3);

      List<Integer> list4 = new ArrayList<Integer>();  
      list4.add(500);
      listOfLists.add(list4);

      iterateUsingForEach(listOfLists);
   }
}

Output

[
 [50, 100, ], 
 [2, ], 
 [200, 300,  400, ], 
 [500, ], 
]

Method 2: With the help iterator

For iterating over a list of lists (2nd list) in Java the use of iterators, there are a few steps involved −

  • Retrieve the 2D list that you need to iterate over.

  • Create the primary iterator to iterate over every row of the 2nd list as a separate listing. What to do to get a separate list for every row of the 2D list? You can employ the iterator's next() function.

Syntax

Iterator<List<K>> listOfListsIterator = listOfLists.iterator();

It's worth noting that the next() method returns the iterator as an Object's object. Because of this, you must cast the object that is returned into a list −

Syntax

List<K> list = (List<K>) listOfListsIterator.next();

Make a second iterator to go through each item in each row one at a time. The iterator can be obtained by using the iterator() method on each individual list −

Syntax

Iterator<K> eachListIterator = list.iterator();

Perform any desired operation on each item.

hasNext()

The code demonstrates how to traverse over a 2D list using iterators in Java. It prints the elements of each inner list within square brackets, separated by commas.

Algorithm

  • Step 1 − Retrieve an iterator for the listOfLists variable with the help of listOfLists variable and the iterator() function.

  • Step 2 − Create a loop that iterates via the iterator. The loop keeps going until the iterator's hasNext() method returns true.

  • Step 3 − Obtain the iterator's next element. We are using the the next() method of the iterator to do this.

  • Step 4 − Verify if the element is a list. If it is, then run the iterateUsingIterator() function on the element repeatedly. Otherwise, simply print the element.

  • Step 5 − Repeat steps 3-4 until the iterator is exhausted

Example

import java.util.*;

public class List_of_list {

   public static <K> void
   iterateUsingIterator(List<List<K> > listOfLists){
      Iterator listOfListsIterator
      = listOfLists.iterator();

      System.out.println("[");
      while (listOfListsIterator.hasNext()) {

         // Type cast next() method for converting from Object to List<K>
         List<K> list = new ArrayList<K>();

         list = (List<K>)listOfListsIterator.next();

         // Iterator for list
         Iterator eachListIterator
         = list.iterator();

         System.out.print(" [");
         while (eachListIterator.hasNext()) {
            System.out.print(" " + eachListIterator.next() + ", ");
         }
         System.out.println("], ");
      }
      System.out.println("]");
   }

   // Driver code
   public static void main(String[] args){

      // List of Lists
      ArrayList<List<Integer> > listOfLists
      = new ArrayList<List<Integer> >();

      List<Integer> list1
      = new ArrayList<Integer>();
      list1.add(150);
      list1.add(210);
      listOfLists.add(list1);

      List<Integer> list2
      = new ArrayList<Integer>();
      list2.add(1);
      listOfLists.add(list2);

      List<Integer> list3
      = new ArrayList<Integer>();
      list3.add(200);
      list3.add(300);
      list3.add(400);
      listOfLists.add(list3);

      iterateUsingIterator(listOfLists);
   }
}

Output

[
 [ 150,  210, ], 
 [ 1, ], 
 [ 200,  300,  400, ], 
]

Conclusion

Iterating over a 2D list, often known as a list of lists, allows Java programmers to analyse data that is stored in two dimensions.

Akin to a chessboard, it offers an adaptable structure for classifying and navigating information. Iterating over a 2D list can be done in one of two ways: utilising loops or iterators. Both methods let you navigate the list's rows and columns for effective data manipulation and analysis.

Updated on: 18-Oct-2023

533 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements