{

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 with objects in a single line.

Normally, You can create and insert into an ArrayList with 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 create and initialize 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 List class is an immutable class and not possible with ArrayList.

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

And also other way to create immutable list with 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 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 of methods. You can check more about java9 of method.

The same way we can create Set and Map using 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 Stream.of() method and returns 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

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.