A List is an order collection that can store elements of any type, including duplicates and null values. In Java, a list can store another list as its element, which is referred to as a List of lists, nested list, or 2D list. As an example consider the following figure which shows a couple of single lists and a list of lists (nested lists):
From this figure, you can notice that each element of a list of lists is also a list.
This write-up presents a complete guide on a list of lists in Java using different examples.
How to Create/Declare an Empty List of Lists in Java
The new operator is the most convenient way of creating an empty (mutable) list of lists in Java. To do that, first, import the necessary classes like List and ArrayList from the “java.util” package and then use the new operator as follows:
import java.util.*;
class ListOfListsExample
{
public static void main(String[] args)
{
List<List<String>> exampleLists = new ArrayList<>();
System.out.println("The Created List: " + exampleLists);
}
}
In the main method, first, we create a string-type “exampleLists” using the new operator. After this, we print the created list on the console:
After this, you can create different lists of your choice and add them to this nested list using the add() method.
How to Create/Declare a Nested List in Java
To create a nested list(list of lists) in Java, you can use the “add()” method, the “Arrays.asList()” method, or the Java 8 “Stream.of()” method.
Method 2: Create a Nested List Using Arrays.asList()
The asList() is a built-in method of the Arrays class that retrieves a fixed-size list based on the provided array. This method creates an immutable list of lists, however, you can use it with the new ArrayList object to create a mutable list. It is capable of creating a list of lists in a single line, as shown below:
package javaBeat;
import java.util.*;
class ListOfListsExample {
public static void main(String[] args) {
List<List<String>> exampleLists = Arrays.asList(
Arrays.asList("Joseph","Mike", "John"),
Arrays.asList("Alex", "Ambrose", "Seth"),
Arrays.asList("Roman", "Paul"));
System.out.println("The Create ListOfLists: " + exampleLists);
}
}
In the above code, we create a list of lists named “exampleLists” using the Arrays.asList() method. Since, each element of a list of lists is also a list, so we use the asList() method three times to add three lists as elements of the exampleLists. On successful execution, you will get the following output on the console:
Alternatively, you can create different lists separately and then use the asList() method to create a new list of lists:
package javaBeat;
import java.util.*;
class ListOfListsExample {
public static void main(String[] args) {
List<String> empNames = Arrays.asList("Joseph","Mike", "John");
List<Integer> empAges = Arrays.asList(25, 24, 27);
List<String> designation = Arrays.asList("Author", "Team Lead", "Manager");
List<List<? extends Object>> exampleLists = Arrays.asList(empNames, empAges, designation);
System.out.println("The Create ListOfLists: " + exampleLists);
}
}
In this code, first, we create three lists of different types. After that, we apply the asList() method to create a list of lists from the provided lists. Finally, we print the created list of lists on the console:
Method 2: Create a List of Lists Using add()
The add() is a built-in method of the List interface that adds/inserts elements to a list. You can create a list of lists using the add() method by adding different lists into a nested list:
package javaBeat;
import java.util.ArrayList;
import java.util.List;
class ListOfListsExample {
public static void main(String[] args) {
//creating different lists
List<String> empNames = new ArrayList<>();
List<Integer> empAges = new ArrayList<>();
List<String> designation = new ArrayList<>();
List<List<? extends Object>> exampleLists = new ArrayList<>();
//adding elements to lists
empNames.add("Joseph");
empNames.add("Mike");
empNames.add("John");
empAges.add(25);
empAges.add(24);
empAges.add(27);
designation.add("Author");
designation.add("Team Lead");
designation.add("Manager");
//Creating a List of Lists
exampleLists.add(empNames);
exampleLists.add(empAges);
exampleLists.add(designation);
System.out.println("The Created List of Lists: " + exampleLists);
}
}
First, we create three simple lists and a nested list using the new operator. After this, we use the add() method to add/insert new elements to each list. Finally, we use the add() method to add the given lists as elements of the nested list:
Method 3: Create a List of Lists Using Stream.of()
The “Stream.of()” is one of the Java 8 stream API methods that can be used with the collect() method to create a List of Lists. Let’s learn how to do it using the following code block:
package javaBeat;
import java.util.*;
import java.util.stream.*;
class ListOfListsExample {
public static void main(String[] args) {
// creating different lists
List<String> empNames = new ArrayList<>();
List<Integer> empAges = new ArrayList<>();
List<String> designation = new ArrayList<>();
// adding elements to lists
empNames.add("Joseph");
empNames.add("Mike");
empNames.add("John");
empAges.add(25);
empAges.add(24);
empAges.add(27);
designation.add("Author");
designation.add("Team Lead");
designation.add("Manager");
// Creating a List of Lists from the given lists
List<List<? extends Object>> exampleLists = Stream.of(empNames, empAges, designation).collect(Collectors.toList());
System.out.println("The Created List of Lists: " + exampleLists);
}
}
In the above code, first, we import the required classes from “java.util” package and Java 8 stream functionality. After this, we created three different lists and added elements to them. Finally, we use the “Stream.of()” method to create a stream of provided lists and the collect(Collectors.toList()) method to collect them in a list:
How to Iterate a Nested List in Java?
To iterate a list of lists in Java, you can use the nested for-each loop or forEach() method. We will demonstrate the working of each method using examples.
- Iterate a List of Lists Using Nested For Each Loop
The nested enhanced for loop or for-each loop is the simplest way of iterating a list of lists. The outer for loop iterates over each list while the inner for loop iterates over each element of the inner list:
System.out.println("The Nested List: ");
for(List list : exampleLists)
{
for(Object i : list)
{
System.out.print( i+ ", ");
} }
In the above code, we use nested enhanced for-loop to iterate over an already created list of lists named exampleLists. The print() method is used within the inner loop the print each element of the nested list of lists:
- Iterate a List of Lists Using forEach()
You can use the Java 8 forEach() method to iterate over the elements of a list of lists. This is a concise and convenient way of iterating a Java list of lists:
System.out.println("The Nested List: ");
exampleLists.forEach((list) -> {
list.forEach((listelement) -> System.out.print(listelement + ", "));
});
}
How to Access an Inner List in Java?
You can access any specific inner list of a nested list by using the get() method. For this purpose, specify the index of the inner list as a parameter to the get() method. For instance, the following code accesses an inner list whose index is 2 (third inner list):
System.out.println(exampleLists.get(2));
How to Access Elements of an Inner List in Java?
To access a specific element of an inner list, you need to use the get() method a couple of times. The first get() method accesses a specific inner list, and the second get() method accesses a specific element of that particular list. For instance, the below code accesses the second element of the third inner list using the get() method:
System.out.println(exampleLists.get(2).get(1));
How to Update or Modify an Outer List in Java?
You can modify a mutable outer list according to your needs. For instance, to remove/eliminate a specific list element, you can utilize the remove() method with the desired index. The following code removes the third element of the exampleLists:
System.out.println("Removed Element: " + exampleLists.remove(2));
System.out.println("Modified List of Lists: " + exampleLists);
Similarly, you can use other List methods to modify a nested list, such as add(), addAll(), removeAll(), etc.
How to Update or Modify an Inner List in Java?
To update an inner list, first, you need to access that particular list using the get() method, and then you can use a list method to perform the desired functionality.
In the following code, the “exampleLists.get(2).remove(2)” removes the third element of the third list:
System.out.println("Removed Element: " + exampleLists.get(2).remove(2));
System.out.println("Modified List of Lists: " + exampleLists);
How to Find the Length of a List of Lists in Java?
To find the length of a nested list, you can simply use the size() method with dot syntax:
System.out.println("Size of Nested List: " + exampleLists.size());
If you want to compute all the elements of the nested lists, use the nested for-each loop and increment the counter on each iteration:
int count =0;
for(List list : exampleLists)
{
for(Object i : list)
{
count++;
}
}System.out.println("Total Elements in a List: " + count);
How to Import a CSV File into a List of Lists(Nested List) in Java?
A common use case of nested lists is importing the content of a CSV file into a list of lists. To do this, import the necessary classes from the “java.io” and “java.util” packages:
package javaBeat;
import java.io.*;
import java.util.*;
class ListOfListsExample { public static void main(String[] args) {
String readFile = "greetings.txt";
String readLine;
List<List<String>> readCSV = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(readFile)))
{
while((readLine = br.readLine()) != null)
{
String[] val = readLine.split(",");
readCSV.add(Arrays.asList(val));
}
}
catch (IOException excep)
{
System.out.println(excep);
}
for (List<String> lineByLine : readCSV)
{
System.out.println(lineByLine);
}
}
}
In the above code:
- First, we create a string-type variable and initialize it with a file that we want to read.
- Next, we create a string-type nested list in which we will store the content of the selected CSV file.
- In the try block, we use the BufferedReader class to read the content of the selected CSV file.
- Within the try block, we use a loop with the readLine() method to read the data/content of the file line by line. This process will keep going until the file contains the content.
- In the while loop, we use the split() method to split the file content from a “,” and store it in a String array “val”. In the very next line, the add() is used along with the asList() method to add this data line by line into a nested list “readCSV”.
- The catch block catches the possible I/O exceptions and prints them on the console.
- Finally, an enhanced for loop is used to traverse and print the content of the nested list.
This way, you can import a CSV file into a string-type list of lists in Java.
How to Flatten a 2-D(Nested) List in Java?
You can use different methods like flatMap(), reduce(), Guava Library, etc., to flatten a nested(list of lists) in Java. To learn the practical implementation of these methods, you can read our dedicated guide on “How to Flatten a List of Lists in Java”.
Final Thoughts
A list containing some other lists as its elements is known as a List of Lists, nested list, or a 2d list. Nested lists are useful in various use cases, such as to import the content of a CSV file into a list of lists, to keep multiple sets of related data in a single list, etc.
In Java, users can create a list of lists via methods like Arrays.asList(), add(), or Stream.of(). Once a list of lists is created, you can iterate it via the for each loop or forEach() method. Also, you can modify a mutable list of lists according to your preferences. For instance, you can add or remove new/unwanted elements to/from a nested list, respectively.