Last Updated:

How to Create and Initialize a List in a Single Line in Java

The trick in this article will allow you to create and initialize an ArrayList just like an array. This technique will save your time when testing the program and speed up its work.

Create and initialize a List on a single line

First, we need the Arrays.asList() method. It is in the java.util.* package and acts as a link between the array and the list in Java. With this method, we will be able to quickly create a list from an array, while creating and initializing the list will take place in one line:

The result of the program:

Remember that Arrays.asList() returns java.util.List, not an ArrayList or LinkedList. It's also worth noting that the list returned by Arrays.asList() has a fixed length that will prevent you from adding or removing an item. The Add() and remove() methods will throw an UnsupportedOperationException if you try to add or remove an item from the list.