List of lists Java: What is it, how to create and use it in Java

List of lists Java is generally useful when you are trying to read a CSV file and you need to handle list of lists to get it in memory, perform some processing and write back to another CSV file. In this blog, we will introduce what list of lists Java is, how to create and use it in Java.

What is list of lists Java?

The Java List interface is a sub-type of the Java Collection interface. This is the standard interface that inherits the Collection interface of Java.

Given below is a class diagram of the Java List interface.

List of lists java
Java List Class Diagram

How to create list of lists Java

You can make use of any of the methods given below to create list of lists Java

1. Using The asList Method

The method asList () is already covered in detail in the Arrays topic. You can create an immutable list using the array values.

The general syntax is:

List<data_type> listname = Arrays.asList(array_name);

Here, the data_type should match that of the array.

The above statement creates an immutable list. If you want the list to be mutable, then you have to create an instance of the list using new and then assign the array elements to it using the asList method.

This is as shown below:

List<data_type> listname = new ArrayList<>(Arrays.asList(array_name));

Let’s implement a program in Java that shows the creation and initialization of the list using the asList method.

import java.util.*;
public class Main
{
public static void main(String[] args) {
//array of strings
 string[] strArray = {"Delhi", "Mumbai", "Kolkata", "Chennai"};
//initialize an immutable list from array using asList method list <String> mylist = Arrays.asList(strArray);
//print the list
System.out.println("Immutable list:");
for(String val : mylist){
System.out.print(val + " ");
}
System.out.println("\n");
//initialize a mutable list(arraylist) from array using asList method
 list<String> arrayList = new ArrayList<>(Arrays.asList(strArray));
System.out.println("Mutable list:");
//add one more element to list
arrayList.add("Pune");
//print the arraylist
for(String val : arrayList){
System.out.print(val + " ");
}
}

Output:

List of lists java

In the above program, we have created the immutable list first using the asList method. Then, we create a mutable list by creating an instance of ArrayList and then initializing this ArrayList with values from the array using the asList method.

Note that as the second list is mutable, we can also add more values to it.

#2) Using List.add()

As already mentioned, as the list is just an interface it cannot be instantiated. But we can instantiate classes that implement this interface. Therefore to initialize the list classes, you can use their respective add methods which is a list interface method but implemented by each of the classes.

If you instantiate a linked list class as below:

List<Integer> llist = new LinkedList<Integer> ();

Then, to add an element to a list, you can use the add method as follows:

llist.add(3);

There is also a technique called “Double brace initialization” in which the list is instantiated and initialized by calling the add method in the same statement.

This is done as shown below:

List<Integer> llist = new LinkedList<Integer> (){{ add(1); add(3);}};

The above statement adds the elements 1 and 3 to the list.

The following program shows the initializations of the list using the add method. It also uses the double brace initialization technique.

import java.util.*;  
public class Main {
 public static void main(String args[])   { 
// ArrayList.add method 
list<String> str_list = new ArrayList<String>(); str_list.add("Java"); 
str_list.add("C++"); 
System.out.println("ArrayList : " + str_list.toString());
  // LinkedList.add method 
List<Integer> even_list = new LinkedList<Integer>(); 
even_list.add(2); 
even_list.add(4); 
System.out.println("LinkedList : " + even_list.toString());
  // double brace initialization - use add with declaration & initialization
List<Integer> num_stack = new Stack<Integer>(){{ add(10);add(20); }}; 
System.out.println("Stack : " + num_stack.toString()); 
} 
}

Output:

Initializations of the list using the add method

This program has three different list declarations i.e. ArrayList, LinkedList, and Stack.

ArrayList and LinkedList objects are instantiated and then the add methods are called to add elements to these objects. For stack, double brace initialization is used in which the add method is called during the instantiation itself.

#3) Using Collections Class Methods

The collections class of Java has various methods that can be used to initialize the list.

Some of the methods are:

  • addAll

The general syntax for collections addAll method is:

List<dataType> listname = Collections.EMPTY_LIST;
Collections.addAll(listname = new ArrayList<datatype>(), values…);

Here, you add values to an empty list. The addAll method takes the list as the first parameter followed by the values to be inserted in the list.

  • unmodifiableList()

The method ‘unmodifiableList()’ returns an immutable list to which the elements cannot be added nor deleted.

The general syntax of this method is as follows:

List<datatype> listname = Collections.unmodifiableList(Arrays.asList(values…));

The method takes list values as parameters and returns a list. If at all you try to add or delete any element from this list, then the compiler throws an exception UnsupportedOperationException.

  • singletonList()

The ‘singletonList’ method returns a list with a single element in it. The list is immutable.

The general syntax for this method is:

List<datatype> listname = Collections.singletonList(value);

The following Java program demonstrates all the three methods of the Collections class discussed above.

import java.util.*;
public class Main {
public static void main(String args[])
{
// empty list
List<Integer> list = new ArrayList<Integer>();
 // Instantiating list using Collections.addAll()
Collections.addAll(list, 10, 20, 30, 40);
 // Print the list
System.out.println("List with addAll() : " + list.toString());
 // Create& initialize the list using unmodifiableList method
List<Integer> intlist = Collections.unmodifiableList(
Arrays.asList(1,3,5,7));
 // Print the list
System.out.println("List with unmodifiableList(): " + intlist.toString());
 // Create& initialize the list using singletonList method
List<String> strlist = Collections.singletonList("Java");
 // Print the list
System.out.println("List with singletonList(): " + strlist.toString());
 }
}

Output:

Three methods of the Collections class

#4) Using Java8 Streams

With the introduction of streams in Java 8, you can also construct a stream of data and collect them in a list.

The following program shows the creation of a list using stream.

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String args[])
{
   // Creating a List using toList Collectors method list<String> list1 = Stream.of("January", "February", "March", "April", "May") .collect(Collectors.toList());
 // Print the list
System.out.println("List from Java 8 stream: "+ list1.toString());
}
}

Output:

The above program collects the stream of string into a list and returns it. You can also use the other Collectors methods like ‘toCollection’, ‘unmodifiableList’ etc. apart from asList in the collect function.

5. Java 9 List.of() Method

A new method is introduced in Java 9, List.of() which takes any number of elements and constructs a list. The list constructed is immutable.

import java.util.List;
public class Main {
public static void main(String args[])  {
// Create a list using List.of()
List<String> strList = List.of("Delhi", "Mumbai", "Kolkata");
// Print the List
System.out.println("List using Java 9 List.of() : " + strList.toString());
}
}

Output:

Java 9 List.of() method

List Example

Given below is a complete example of using a list interface and its various methods.

import java.util.*;
public class Main {
 public static void main(String[] args)
 {
 // Creating a list
 List<Integer> intList = new ArrayList<Integer>();
 //add two values to the list
intList.add(0, 10); 
intList.add(1, 20);  
System.out.println("The initial List:\n" + intList);
   // Creating another list
 List<Integer> cp_list = new ArrayList<Integer>();
 cp_list.add(30);
 cp_list.add(40);
 cp_list.add(50);
  // add list cp_list to intList from index 2
 intList.addAll(2, cp_list);
 System.out.println("List after adding another list at index 2:\n"+ intList);
  // Removes element from index 0
 intList.remove(0);
 System.out.println("List after removing element at index 0:\n" + intList);
  // Replace value of last element
 intList.set(3, 60);
 System.out.println("List after replacing the value of last element:\n" + intList);
 } 
}          

Output:

The above program output shows the various operations performed on an ArrayList. First, it creates and initializes the list. Then it copies the contents of another list to this list and also removes an element from the list. Finally, it replaces the last element in the list with another value.

How to to use List of Lists Java

#1) Using For Loop/Enhanced For Loop

The list is an ordered collection that can be accessed using indices. You can use for loop that is used to iterate using the indices to print each element of the list.

Java has another version of for loop knows as enhanced for loop that can also be used to access and print each element of the list.

The Java program shown below demonstrates the printing of list contents using for loop and enhanced for loop.

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays; 
class Main{
public static void main (String[] args)
{
//string list
list<String> list = Arrays.asList("Java", "Python", "C++", "C", "Ruby");
//print list using for loop
System.out.println("List contents using for loop:");
for (int i = 0; i <list.size(); i++) {
System.out.print(list.get(i) + " ");
}
//print list using enhanced for loop
System.out.println("\n\nList contents using enhanced for loop:");
for (String s : list) {
System.out.print(s + " ");
}
}
}

Output:

#2) Using The toString Method

The method ‘toString()’ of the list interface returns the string representation of the list.

The program below demonstrates the usage of the toString() method.

import java.util.List;
import java.util.ArrayList;
class Main{
public static void main (String[] args){
//initialize a string list
  List<String> list = new  ArrayList<String>(){{add("Python");add("C++");add("Java");}};
// string representation of list using toString method
System.out.println("List contents using toString() method:" + list.toString());
}
}

Output:

Usage of the toString() method

List Converted To An Array

The list has a method toArray() that converts the list to an array. Once converted to an array, you can use the array methods discussed in the respective topic to print the contents of this array. You can either use for or enhanced for loop or even toString method.

The example given below uses the toString method to print the array contents.

import java.util.*;
class Main
{
public static void main (String[] args)
{
//list of odd numbers
list<Integer> oddlist = Arrays.asList(1,3,5,7,9,11); 
// using List.toArray() method
System.out.println("Contents of list converted to Array:");
System.out.println(Arrays.toString(oddlist.toArray()));
}
}

Output:

Using Java 8 Streams

Streams are introduced in Java 8. You can make use of streams to loop through the list. There are also lambdas using which you can iterate through the list.

The program below shows the usage of streams to iterate through the list and display its contents.

import java.util.*; 
class Main{
public static void main (String[] args){
//list of even numbers
List<Integer> evenlist = Arrays.asList(2,4,6,8,10,12,14);
// print list using streams
System.out.println("Contents of evenlist using streams:");
evenlist.stream().forEach(S ->System.out.print(S + " "));
}
}

Output:

Usage of streams to iterate through the list

Apart from the methods discussed above, you can use list iterators to iterate through the list and display its contents. We will have a complete article on the list iterator in the subsequent tutorials.

List Of Lists

Java list interface supports the ‘list of lists’. In this, the individual elements of the list is again a list. This means you can have a list inside another list.

This concept is very useful when you have to read data from say CSV files. Here, you might need to read multiple lists or lists inside lists and then store them in memory. Again you will have to process this data and write back to the file. Thus in such situations, you can maintain a list of lists to simplify data processing.

The following Java program demonstrates an example of a Java list of lists.

In this program, we have a list of lists of type String. We create two separate lists of type string and assign values to these lists. Both these lists are added to the list of lists using the add method.

To display the contents of the list of lists, we use two loops. The outer loop (foreach) iterates through the lists of lists accessing the lists. The inner foreach loop accesses the individual string elements of each of these lists.

import java.util.ArrayList;
import java.util.List; 
public class Main {
 public static void main(String[] args) {
//create list of lists
List<ArrayList<String>> java_listOfLists = new ArrayList<ArrayList<String>>();
//create a language list and add elements to playlist
Array<String> lang_list = new ArrayList<String>();
lang_list.add("Java");
lang_list.add("C++");
//add language list to java list of list java_listOfLists.add(lang_list); 

//create a city list and add elements to it
ArrayList<String> city_list = new ArrayList<String>();
city_list.add("Pune");
city_list.add("Mumbai");
//add the city list to java list of lists
java_listOfLists.add(city_list); 
//display the contents of list of lists     System.out.println("Java list of lists contents:");
java_listOfLists.forEach((list)  ->                 //access each list
{
list.forEach((city)->System.out.print(city + " ")); //each element of inner list
});
}
}

Output:

Example of a Java list of lists

Java list of lists is a small concept but is important especially when you have to read complex data in your program.

Any help with Java development services? Let’s ArrowHiTech help you!

If you’re considering web development services, you can explore more about us – ArrowHiTech. Above all, we are proud to be one of the most well-established outsourcing companies all around the world. In addition, with over 12 years of experience, we can provide the best Java development services for your business.

ArrowHiTech services

So, if you have any questions, don’t hesitate to contact us

Tags

Share