Nested ArrayList in Java

In Java, ArrayList is a class of Java Collections framework that provides us with the concept of resizable arrays. It is a list of arrays where we can automatically adjust its capacity by adding or removing elements. It is therefore also known as Dynamic Arrays.

This tutorial will discuss and create nested ArrayLists in Java.

A nested ArrayList is a list within a list. Due to the dynamic nature of ArrayLists, we can have multiple dimensions of the list added on as per our requirement. Individual elements of such a list are lists themselves.

Remember to import the java.util.Collections as it is part of the Collections framework. We create a nested ArrayList in the following example.

import java.util.*;
public class ABC{
    public static void main(String args[]){
    
    List<ArrayList<Integer>> a = new ArrayList<>(); 

    ArrayList<Integer> al1 = new ArrayList<Integer>();
    ArrayList<Integer> al2 = new ArrayList<Integer>();
    ArrayList<Integer> al3 = new ArrayList<Integer>();

    al1.add(1);
    al1.add(2);
    al1.add(3);
    
    al2.add(4);
    al2.add(5);
    al2.add(6);
    
    al3.add(7);
    al3.add(8);
    al3.add(9);
    
    a.add(al1);
    a.add(al2);
    a.add(al3);

    for(ArrayList obj: a){
        ArrayList<Integer> temp = obj; 
        for(Integer num : temp){
            System.out.print(num + " "); 
        }
        System.out.println(); 
    }
}
}

Output:

1 2 3
4 5 6
7 8 9

In the above example, we have successfully created a two-dimensional nested ArrayList and print it. We create three individual ArrayLists al1, al2, al3, and add them as elements to a single ArrayList a. Note that the final result also resembles a matrix.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Java ArrayList

  • Sort Objects in ArrayList by Date in Java
  • Compare ArrayLists in Java
  • Merge Sort Using ArrayList in Java
  • Convert ArrayList to Set in Java