This post will discuss different ways to initialize a List of Lists in Java.

1. Using List.add() method

You can declare a List of Lists in Java, using the following syntax. It uses the new operator to instantiate the list by allocating memory and returning a reference to that memory.

Download  Run Code

Output:

[]

 
To add elements to it, call the add() method. Since each element of a List of Lists is a List itself, pass the new List instance to the add() method. Be extra careful not to pass the same mutable instance of a list to the add() method again.

Download  Run Code

Output:

[]
[]
[]

 
You can easily add lists of a specific size, initialized by nulls or with some desired value.

Download  Run Code

Output:

[null, null, null]
[null, null, null]
[null, null, null]

2. Using Arrays.asList() method

You can initialize a List of Lists in a single line in the following manner using the Arrays.asList() method:

Download  Run Code

Output:

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

 
With Java 9 onwards, you can use the static factory method List.of().

Download  Run Code

Output:

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

 
Note that both Arrays.asList() and List.of() method creates an unmodifiable instance of the list. If you need a mutable instance, wrap each list instance using the ArrayList constructor.

Download  Run Code

Output:

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

3. Using IntStream

Finally, with Java 8 you can use IntStream to initialize a List of Lists as demonstrated below:

Download  Run Code

Output:

[1, 1, 1, 1]
[2, 2, 2, 2]
[3, 3, 3, 3]

That’s all about initializing a List of Lists in Java.