Signup/Sign In

List Initialization in a Single Line

The List is an interface in Java and is implemented by classes like the ArrayList and the LinkedList. The List interface implements the Collection interface.

In this tutorial, we will learn some one-liners to initialize a List in Java.

Arrays.asList() Method

We can create a List from an array by using the asList() method. This method can take varargs, so we don't even need an array to initialize the list. We can directly pass the elements to this method.

import java.util.Arrays;
import java.util.List;

public class Demo
{
	public static void main(String[] args)
	{
		List<String> listOfStrings = Arrays.asList("Justin", "Jessica", "Simon", "Harry");
		System.out.print(listOfStrings);
	}
}


[Justin, Jessica, Simon, Harry]

The returned instance from this method is a List backed by the input array. This makes the initialized list fixed in size, and we cannot add more elements to it. If we try to add an element, then we will get a UnsupportedOperationException. This scenario is demonstrated by the code below.

import java.util.Arrays;
import java.util.List;
public class Demo
{
	public static void main(String[] args)
	{
		List<String> listOfStrings = Arrays.asList("Justin", "Jessica", "Simon", "Harry");
		listOfStrings.add("Victor");//Error
	}
}


Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.AbstractList.add(AbstractList.java:153)
at java.base/java.util.AbstractList.add(AbstractList.java:111)
at Demo.main(Demo.java:9)

Another thing to note is that the array and the list will have shared references to the objects. No new objects will be created and added to the list. We can verify this by printing the object and viewing the unique hashcode. In the code output below, the hashcode of the object from the array and the list are the same, implying that it is the same object.

import java.util.Arrays;
import java.util.List;

public class Demo
{
	public static void main(String[] args)
	{
		Object o1 = new Object();
		Object o2 = new Object();
		Object o3 = new Object();
		
		Object[] objectArr = {o1, o2, o3};
		List<Object> listOfObjects = Arrays.asList(objectArr);//Creating a List of Objects
		System.out.println("Object o2 from Array: " + objectArr[1]);
		System.out.println("Object o2 from List: " + listOfObjects.get(1));
	}
}


Object o2 from Array: java.lang.Object@36baf30c
Object o2 from List: java.lang.Object@36baf30c

Using Java 8 Streams

Streams can also initialize lists in Java. We can use the Stream.of() method to create a Stream. Next, we will use the collect() method to collect the stream elements in the List.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo
{
	public static void main(String[] args)
	{
		List<String> listOfStrings = Stream.of("Justin", "Jessica", "Simon")
										   .collect(Collectors.toList());
		System.out.print(listOfStrings);
	}
}


[Justin, Jessica, Simon]

Using List.of() Method

The List.of() method was introduced in Java 9 and can initialize a list in a single line of code. We need to pass the elements to this method, and it will return a List instance. Java 9 contains several overloaded versions for this method to provide better performance. It also contains a varargs overloaded method to deal with more number of elements.

import java.util.List;

public class Demo
{
	public static void main(String[] args)
	{
		List<String> listOfStrings = List.of("Justin", "Jessica", "Simon");
		System.out.print(listOfStrings);
	}
}


[Justin, Jessica, Simon]

Note that the returned List is immutable and cannot be altered. If we try to modify the list, we will get an UnsupportedOperationException.

import java.util.List;
public class Demo
{
	public static void main(String[] args)
	{
		List<String> listOfStrings = List.of("Justin", "Jessica", "Simon");
		listOfStrings.add("Victor");//Error
	}
}


Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:73)
at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:77)
at Demo.main(Demo.java:8)

Double Brace Syntax

We can use the double-brace syntax to initialize a list in Java. The outer set of braces are used to declare an anonymous inner class that extends the object type.

The inner pair of braces is called the instance initialization block, and we will use it to add elements to our list.

This approach is not recommended because it creates a new class every time. It also holds hidden references to enclosing instances, which may lead to memory leaks.

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

public class Demo
{
	public static void main(String[] args)
	{
		List<String> listOfStrings = new ArrayList<String>() {
			{
			    add("Justin");
			    add("Jessica");
			    add("Simon");
			}
		};
		
		System.out.print(listOfStrings);
	}
}


[Justin, Jessica, Simon]

External Libraries

We can use the Guava or the Apache Commons libraries to initialize a list in Java.

Using Apache Commons Collections

We can use the unmodifiableList() method of the ListUtils class to create an unmodifiable list. We can pass an existing list to this method. Or we can use the Arrays.asList() method inside the unmodifiableList().

import java.util.List;
import org.apache.commons.collections4.ListUtils;
import java.util.Arrays;

public class Demo
{
	public static void main(String[] args)
	{
		List<String> listOfStrings = ListUtils.unmodifiableList(
									 Arrays.asList("Justin", "Jessica", "Simon", "Harry")
									 );
		System.out.print(listOfStrings);
	}
}


[Justin, Jessica, Simon, Harry]

This method is not frequently used as we can accomplish the same result with the help of just the Arrays.asList() method.

Using Guava Library

The Guava library can initialize a mutable and immutable list. The newArrayList() method of the Lists class takes the elements as parameters and returns a mutable ArrayList initialized with those elements.

import java.util.List;
import com.google.common.collect.Lists;
public class Demo
{
	public static void main(String[] args)
	{
		List<String> listOfStrings = Lists.newArrayList("Justin", "Jessica", "Simon");
		System.out.print(listOfStrings);
	}
}


[Justin, Jessica, Simon]

To create an immutable list, we will use the ImmutableList.of() method. Guava provides several overloaded versions of this method for better performance. It also has a varargs overloaded method to deal with more number of elements.

import java.util.List;
import com.google.common.collect.ImmutableList;

public class Demo
{
	public static void main(String[] args)
	{
		List<String> listOfStrings = ImmutableList.of("Justin", "Jessica", "Harry");
		System.out.print(listOfStrings);
	}
}


[Justin, Jessica, Harry]

Summary

In this tutorial, we learned the different ways to initialize a List in Java by using just a single line of code. We discussed several methods of creating mutable as well as immutable lists. Any one of the above approaches can be used as all of them have comparable performance. However, the double-braces method is not recommended as it leads to a lot of overhead.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.