New list Java

This post will discuss various methods to initialize a list in Java in a single line.

Java is often criticized for its verbosity. For example, creating a list containing n elements involves constructing it, storing it in a variable, invoking the add[] method on it n times, and then maybe wrapping it to make it unmodifiable:

List list = new ArrayList[];

list = Collections.unmodifiableList[list];


This post will discuss various methods to initialize a list in a single expression.

1. Using Arrays.asList[] method

Arrays.asList[] returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, it is impossible to add elements to the list or remove elements from it. The list will throw an UnsupportedOperationException if any resize operation is performed on it.

List fixedLengthList = Arrays.asList["C", "C++", "Java"];


If we need a list that can expand or shrink, we can use:

List list = new ArrayList[Arrays.asList["C", "C++", "Java"]];

2. Using Java Collections

Collections class consists of several static methods that operate on collections and return a new collection backed by a specified collection.

⮚ Collections.addAll[]

Collections.addAll[] adds all the specified elements to the specified collection. Elements to be added may be specified individually or as an array. When elements are specified individually, this method provides a convenient way to add a few elements to an existing collection:

List list = Collections.EMPTY_LIST;

Collections.addAll[list = new ArrayList[], "C", "C++", "Java"];

⮚ Collections.unmodifiableList[]

Alternatively, one can populate a collection using a copy constructor from another collection. One such method is Collections.unmodifiableList[] returns an unmodifiable view of the specified list. Any attempts to modify the returned list will result in an UnsupportedOperationException.

List unmodifiableList = Collections.unmodifiableList[

Arrays.asList["C", "C++", "Java"]];

⮚ Collections.singletonList[]

If we want a list containing only a single element, we can use Collections.singletonList[] that returns an immutable list containing that element. The list will throw an UnsupportedOperationException if any modification operation is performed on it.

List list = Collections.singletonList["Java"];

3. Using Double Brace Initialization

Another alternative is to use Double Brace Initialization. This creates an anonymous inner class with just an instance initializer in it. We should best avoid this technique as it costs an extra class at each usage. It also holds hidden references to the enclosing instance and any captured objects. This may cause memory leaks or problems with serialization.

List list = new ArrayList[] {{

4. Using Java 8

We can use the Java 8 Stream to construct small lists by obtaining stream from static factory methods and accumulating the input elements into a new list using collectors. For example,

⮚ Collectors.toList[]

Collectors.toList[] returns a Collector that accumulates the input elements into a new List.

List list = Stream.of["C", "C++", "Java"]

.collect[Collectors.toList[]];

⮚ Collectors.toCollection[]

The streams collectors make no guarantee on the type of the List returned by toList[]. To ensure the returned List is ArrayList, we can use toCollection[Supplier], as shown below:

List list = Stream.of["C", "C++", "Java"]

.collect[Collectors.toCollection[ArrayList::new]];

⮚ Collectors.collectingAndThen[]

We could adapt a collector to perform an additional finishing transformation. For example, we could adapt the toList[] collector to always produce an unmodifiable list with:

List list = Stream.of["C", "C++", "Java"]

.collect[Collectors.collectingAndThen[Collectors.toList[],

Collections::unmodifiableList]];

5. Using Java 9

Java 9 made it convenient to create instances of a list with small numbers of elements by providing Lists.of[] static factory methods that create compact, unmodifiable instances. For example,

List unmodifiableList = List.of["C", "C++", "Java"];


Java 9 provides 12 overloaded versions of this method:

static List of[] static List of[E e1]1 static List of[E e1, E e2] static List of[E e1, E e2, E e3, E e4 E e8, E e9] static List of[E e1, E e2, E e3, E e4 E e8, E e9, E e10]

static List of[E elements]

Note there is a var-args version that can handle any number of elements. The obvious question is: Why Java 9 has included so many extra methods when only var-args can suffice? The reason is subtle runtime performance advantage. The var-args version is likely to run slower than the overloadings that do not use varargs. This is because every invocation of a varargs method will cause an array allocation and initialization and, not to forget, GC overhead.


As per Javadoc, the list instances created by List.of[] have the following characteristics:

  1. They are structurally immutable. Elements cannot be added, removed, or replaced. Calling any mutator method will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the lists contents to appear to change.
  2. They disallow null elements. Attempts to create them with null elements result in NullPointerException.
  3. They are serializable if all elements are serializable.
  4. The order of elements in the list is the same as the order of the provided arguments or of the elements in the provided array.
  5. They are value-based. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones. Therefore, identity-sensitive operations on these instances [reference equality [==], identity hash code, and synchronization] are unreliable and should be avoided.

If we need a list that can expand or shrink, we can use:

List list = new ArrayList[List.of["C", "C++", "Java"]];


Please note that unlike static methods on classes, static methods on interfaces are not inherited, so it will not be possible to invoke them via an implementing class nor an instance of the interface type.

6. Using Guava Library

Guava also provides several static utility methods pertaining to list instances. Refer to the following post for details:

Initialize List in Java using Guava

7. Using Apache Commons Collections

Apache Commons Collections ListUtils class provides unmodifiableList[] that returns an unmodifiable list backed by the given list. It throws a NullPointerException if the given list is null and an UnsupportedOperationException if any modification operation is performed on it.

List unmodifiableList = ListUtils.unmodifiableList[

Arrays.asList["C", "C++", "Java"]];

Thats all about initializing List in Java in a single line.


Reference: JEP 269: Convenience Factory Methods for Collections

Video liên quan

Chủ Đề