Initialize a List of Lists in Java

Google Translate Icon

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.

Rate this post

Average rating 4.82/5. Vote count: 22

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?




Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding :)



Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Do NOT follow this link or you will be banned from the site!