How to create list of lists in java

In this posts, we will see how to create a list of lists in java.
You can easily create a list of lists using below syntax

List<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
or
ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();

One of the Usecase

This is generally useful when you are trying to read a CSV file and then you need to handle list of lists to get it in memory, perform some processing and write back to another CSV file.

Let’s take a simple example for list of lists.

package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.List;

public class JavaListOfListsMain {

    public static void main(String[] args) {
        List<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
        ArrayList<String> list1 = new ArrayList<String>();
        list1.add("Delhi");
        list1.add("Mumbai");
        listOfLists.add(list1);

        ArrayList<String> anotherList = new ArrayList<String>();

        anotherList.add("Beijing");
        anotherList.add("Shanghai");
        listOfLists.add(anotherList);

        listOfLists.forEach((list)  -> 
        {
            list.forEach((city)->System.out.println(city));
        }
                );
    }
}

When you run above program, you will get below output.

Delhi
Mumbai
Beijing
Shanghai

Question on list of lists

Can you instantiate List as below

List<List<String>> myList = new ArrayList<ArrayList<String>>();
No, you can't.

Let’s understand the reason for it.
Let’s say you have list as below:

 ArrayList<ArrayList<String>> list1 = new ArrayList<ArrayList<String>>();

Now suppose you could assign that to

    List<List<String>> list2 = list1.

Now, you should be able to do this:

    list2.add(new LinkedList<String>());

But that means you have just added a

LinkedList

  to a list whose elements are supposed to be ArrayList only.That’s why it is not allowed to do it.
That’s all about how to create list of lists in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.