How to Initialization of an ArrayList in one line in Java

You can initialize an ArrayList in one line in Java using the following syntax:

List<Type> list = new ArrayList<>(Arrays.asList(elements));

Here, Type is the type of elements that the list will hold (e.g. Integer, String, etc.), elements is an array of elements of type Type that you want to add to the list, and list is the name of the ArrayList.

For example, to create an ArrayList of integers with the elements 1, 2, and 3, you can use the following code:

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));

Alternatively, you can use the following syntax to initialize an ArrayList in one line:

List<Type> list = Arrays.asList(elements);

This creates a fixed-size list that is backed by the original array.

For example:

List<Integer> list = Arrays.asList(1, 2, 3);

Note that the second syntax creates a list that is fixed-size, meaning that you cannot add or remove elements from it. If you need to modify the list, you should use the first syntax to create a modifiable list.