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


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

Normally, You can create and insert into 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 single line ?

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

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

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

Arraylist Anonymous inner class

This is one of the approach to declare anonymous inner class with new arraylist by double brace syntax.

We can call instance method directly, In this case add method is called The only disadvantage is you creating and extending arraylist i.e subclass.

This is one of the approach 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, This can be used to initialize with 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 java9 version, List and Set classes has overloaded of method. 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 Stream.of() method and returns collection of stream
  • pass this stream to 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 an mutable ArrayList and immutable List using different approaches.

You can choose based on your java version and if you need to update 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.