How to create and initialize ArrayList in java with one line?

This is a short tutorial on how to create an array list and initialize it with objects in a single line.

Normally, You can create and add data into an ArrayList with the below lines of code

ArrayList<String> names = new ArrayList<String>();
places.add("Name1");
places.add("Name2");
places.add("Name3");

How could we refactor the above code with a single line?

Yes, we can do it in multiple ways, This will be helpful to have static fixed data that can be used in unit testing or anywhere.

How to Declare and add data in ArrayList in java with one line?

Let’s discuss creating and initializing multiple ways. These examples used fixed size of elements during declaring List.

Arraylist Anonymous inner class

It is one of the approaches to declare an anonymous inner class with the new ArrayList by double brace syntax.

We can call the instance method directly, In this case add method is called. The only disadvantage is you create and extend ArrayList i.e subclass.

It is one of the approaches to initialize the ArrayList. It should not be used for this purpose.

ArrayList<String> names = new ArrayList<String>() {{
   add("Name1");
add("Name2");
add("Name3");
}};

using List inline initialize

Like a variable initialization, It uses to initialize with the List class The List class is an immutable class and not possible with ArrayList.

List<String> names = ["Name1", "Name2", "Name3"];

And also another way to create an immutable list with the Arrays asList method

List<String> names = Arrays.asList("Name1", "Name2", "Name3");

using Arrays.asList for creating mutable ArrayList

ArrayList constructor accepts List as an argument, List can be created using the Arrays.asList method.

ArrayList<String> names = new ArrayList<>(Arrays.asList("Name1", "Name2", "Name3"));

java9 List of method

with the java9 version, List and Set classes have overloaded methods. You can check more about java9 of method.

In the same way, we can create Set and Map using the of method

List<String> names = List.of("Name1", "Name2", "Name3");

java8 streams

java8 introduced streams for handling and manipulation of collections.

  • First, create a stream of data using the ` method and return collection of stream
  • pass this stream to collect with java.util.stream.Collectors.toList which returns List object
List<String> names = Stream.of("Name1", "Name2", "Name3").collect(toList());

Conclusion

We have learned multiple ways to create a mutable ArrayList and immutable List using different approaches.

You can choose based on your java version and if you need to update the list, use mutable ArrayList.