📜  java list of lists - Java (1)

📅  最后修改于: 2023-12-03 15:15:56.861000             🧑  作者: Mango

Java List of Lists

In Java, a List is a data structure used to store multiple elements. A list can contain any type of objects, including other lists. In this article, we will explore the concept of a list of lists in Java.

Initializing a List of Lists

To create a list of lists in Java, we can use the List interface, which defines the basic operations that can be performed on a list. We can create a list of lists by declaring a List variable and initializing it with a nested list.

List<List<Integer>> listOfLists = new ArrayList<List<Integer>>();

In the above example, we are creating a list of integer lists. We are using the ArrayList implementation of the List interface, which provides a resizable array. We can add elements to the list of lists by using the add method.

List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
List<Integer> list2 = new ArrayList<Integer>();
list2.add(4);
list2.add(5);
list2.add(6);
listOfLists.add(list1);
listOfLists.add(list2);

In the above example, we have created two integer lists and added them to the list of lists. The listOfLists variable now contains two lists, list1 and list2.

Accessing Elements in a List of Lists

To access elements in a list of lists, we can use the get method. The get method returns the element at a specified index. In a list of lists, we need to use two indexes to access an element.

int element = listOfLists.get(0).get(1);

In the above example, we are accessing the element at index 1 in the first list (list1) in the list of lists (listOfLists). The value of element will be 2.

Iterating Over a List of Lists

We can iterate over a list of lists in Java using nested loops. The outer loop iterates over the lists in the list of lists, while the inner loop iterates over the elements in each list.

for (List<Integer> list : listOfLists) {
    for (int element : list) {
        System.out.print(element + " ");
    }
    System.out.println();
}

In the above example, we are iterating over the lists in the list of lists and printing the elements in each list. The output will be:

1 2 3 
4 5 6 
Conclusion

In this article, we have explored the concept of a list of lists in Java. We have seen how to initialize a list of lists, access elements in a list of lists, and iterate over a list of lists. Lists of lists are a powerful data structure that can be used to store and manipulate complex data in Java.