To create a list of lists in Java, you can use the `ArrayList` class to represent the outer list and add `ArrayList` instances as elements to create inner lists.
In this example,
java.util
package.list1
and list2
using the ArrayList
class.listOfLists
using the ArrayList
class.list1
and list2
to the outer list listOfLists
.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(3);
List<String> list2 = new ArrayList<>();
list2.add("a");
list2.add("b");
list2.add("c");
List<List<?>> listOfLists = new ArrayList<>();
listOfLists.add(list1);
listOfLists.add(list2);
System.out.println("List of lists: " + listOfLists);
}
}
List of lists: [[1, 2, 3], [a, b, c]]
In this example,
list3
and list4
.listOfListsEmpty
using the ArrayList
class.list3
and list4
to the outer list listOfListsEmpty
.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list3 = new ArrayList<>();
List<String> list4 = new ArrayList<>();
List<List<?>> listOfListsEmpty = new ArrayList<>();
listOfListsEmpty.add(list3);
listOfListsEmpty.add(list4);
System.out.println("List of lists with empty inner lists: " + listOfListsEmpty);
}
}
List of lists with empty inner lists: [[], []]
In this tutorial, we learned How to create a List of Lists in Java language with well detailed examples.