Multidimensional Collections in Java

Java 8Server Side ProgrammingProgramming

Multidimensional collections are also known as Nested collections. It is a group of objects wherein every group has any number of objects that can be created dynamically. They can be stored in any position as well. In case of arrays, the user would be bound to a specific number of rows and columns, hence multidimensional structure helps create and add elements dynamically.

Syntax of multidimensional arraylist in Java

ArrayList<ArrayList<Object>> object_name = new ArrayList<ArrayList<Object>>();


Following is an example of multidimensional collections in Java −

Import java.util.*;
public class Demo {
   static List multi_dimensional() {
      ArrayList<ArrayList<Integer> > x = new ArrayList<ArrayList<Integer> >();
      x.add(new ArrayList<Integer>());
      x.get(0).add(0, 45);
      x.add(new ArrayList<Integer>(Arrays.asList(56, 67, 89)));
      x.get(1).add(0, 67);
      x.get(1).add(4, 456);
      x.add(2, new ArrayList<>(Arrays.asList(23, 32)));
      x.add(new ArrayList<Integer>(Arrays.asList(83, 64, 77)));
      x.add(new ArrayList<>(Arrays.asList(8)));
      return x;
   public static void main(String args[]) {
      System.out.println("The multidimensional arraylist is :");


The multidimensional arraylist is :
[[45], [67, 56, 67, 89, 456], [23, 32], [83, 64, 77], [8]]


A class named Demo contains a function named ‘multi_dimensional’, that declares an arraylist of arraylist of integers, and the ‘add’ function is used to add elements to it. First, in the 0th position, an element is added. Next, three more elements are added to the row. To the first row, 0th column, one more element is added. Another value is placed in the 1st row of the 4th column. Next, values are added to 2nd, 3rd and 4th rows respectively. In the main function, the function ‘multi_dimensional’ is called and the output is printed on the console.

Published on 14-Sep-2020 12:18:08