Create list Java

Table of Contents

    • One of the Usecase
  • Question on list of lists

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 listOfLists = new ArrayList[];
or
ArrayList listOfLists = new ArrayList[];

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.

Lets take a simple example for list of lists.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package org.arpit.java2blog;
import java.util.ArrayList;
import java.util.List;
public class JavaListOfListsMain {
public static void main[String[] args] {
List listOfLists = new ArrayList[];
ArrayList list1 = new ArrayList[];
list1.add["Delhi"];
list1.add["Mumbai"];
listOfLists.add[list1];
ArrayList anotherList = new ArrayList[];
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

1
2
3
List myList = new ArrayList[];
No, you can't.

Lets understand the reason for it.
Lets say you have list as below:

1
2
3
ArrayList list1 = new ArrayList[];

Now suppose you could assign that to

1
2
3
List list2 = list1.

Now, you should be able to do this:

1
2
3
list2.add[new LinkedList[]];

But that means you have just added a LinkedList to a list whose elements are supposed to be ArrayList only.Thats why it is not allowed to do it.
Thats all about how to create list of lists in java.


import_contacts

You may also like:

Create ArrayList of Objects in Java

How to remove element from Arraylist in java while iterating

Print HashMap in Java

Print LinkedList in java

Java Set to Array

Print ArrayList in Java

How to Deep Copy Arraylist in Java

Initialize ArrayList with values in Java

PriorityQueue in Java 8

2d Arraylist java example

  • 1
  • 2
  • 3
  • 5

Video liên quan

Chủ Đề