Skip to main content

How to Create Nested ArrayList in Java | 2D ArrayList - BlogonCode

Multi-Dimensional ArrayList in Java | Creating and Store Elements in Nested ArrayList

Multi-Dimensional ArrayList in Java | Creating and Store Elements in Nested ArrayList

In Java, ArrayList is Class of Java Collections framework that stores elements with resizable arrays. ArrayList is also called Dynamic Arrays.

Often times, We need to store data in dynamic array rather than static array. So in this tutorial we will seen how we can create, store and print nested or two dimensional arraylist elements.

We will seen two approach for storing nested elements in ArrayList.

  1. Creating Nested ArrayList with Static Elements
  2. Creating Nested ArrayList with Dynamic Elements using Scanner Class

Learn more about ArrayList class :

Example 1 : Nested ArrayList with Static Elements

import java.util.ArrayList;
import java.util.List;

public class NestedArrayList {

    public static void main(String[] args) {
       
        List<ArrayList<Integer>> outerList = new ArrayList<>();

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

        al1.add(1);
        al1.add(2);
        al1.add(3);
       
        al2.add(4);
        al2.add(5);
        al2.add(6);
       
        outerList.add(al1);
        outerList.add(al2);
       
        System.out.println(outerList);

    }
}

Output :

[[1, 2, 3], [4, 5, 6]]

Now lets see how to store user defined elements in nested arraylist

Example 2 : Nested ArrayList with Dynamic (User defined) Elements

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class NestedArrayList {

    public static void main(String[] args) {
       
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Size of ArrayList");
        int size = sc.nextInt();
        List<List<Integer>> outerList = new ArrayList<List<Integer>>();
        List<Integer> innerList = null;
        System.out.println("Insert Elements");
       
        for (int i = 0; i < size; i++) {
            innerList = new ArrayList<Integer>();
            for (int j = 0; j < size; j++) {
                innerList.add(sc.nextInt());
            }
            outerList.add(innerList);
        }
       
        System.out.println(outerList);

    }
}

Output :

Enter Size of ArrayList
2
Insert Elements
1 2 3 4
[[1, 2], [3, 4]]
________________________

Enter Size of ArrayList
4
Insert Elements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]


RECOMMENDED ARTICLES :

 

Comments