Initialization of an ArrayList in one line

In this tutorial, we'll take a look at how to declare and initialize arrays in Java.

In this tutorial, we'll take a look at how to declare and initialize Arraylist in Java.

Java 9 or later:

List<String> strings = List.of("foo", "bar", "baz");

This will give you an immutable List, so it cannot be changed. Which is what you want in most cases where you're prepopulating it.

Java 8 or earlier:

List<String> strings = Arrays.asList("foo", "bar", "baz");

This will give you a List* backed by an array, so it cannot change length. But you can call List.set(...), so it's still mutable.

  • Implementation detail: It's a private nested class inside java.util.Arrays, named ArrayList, which is a different class from java.util.ArrayList, even though their simple names are the same.

Static import

You can make Java 8 Arrays.asList even shorter with a static import:

import static java.util.Arrays.asList;  
...
List<String> strings = asList("foo", "bar", "baz");

Any modern IDE* will suggest and do this for you.

I don't recommend statically importing the List.of method as just of, because it's confusing.

  • For example, in IntelliJ IDEA you press Alt+Enter and select Static import method...

Using Streams

Why does it have to be a List? With Java 8 or later you can use a Stream which is more flexible:

Stream<String> strings = Stream.of("foo", "bar", "baz");

You can concatenate Streams:

Stream<String> strings = Stream.concat(Stream.of("foo", "bar"),
                                       Stream.of("baz", "qux"));

Or you can go from a Stream to a List:

import static java.util.stream.Collectors.toList;
...
var strings = Stream.of("foo", "bar", "baz").toList(); // Java 16

List<String> strings = Stream.of("foo", "bar", "baz").collect(toList()); // Java 8

But preferably, just use the Stream without collecting it to a List.

If you specifically need a java.util.ArrayList* If you want to both prepopulate an ArrayList and add to it afterwards, use

List<String> strings = new ArrayList<>(List.of("foo", "bar"));
strings.add("baz");

or in Java 8 or earlier:

List<String> strings = new ArrayList<>(asList("foo", "bar"));
strings.add("baz");

or using Stream:

import static java.util.stream.Collectors.toCollection;

List<String> strings = Stream.of("foo", "bar")
                             .collect(toCollection(ArrayList::new));
strings.add("baz");

But again, it's better to just use the Stream directly instead of collecting it to a List.