Initialize List with Values in Java
In this tutorial, we’ll learn different ways to initialize List, ArrayList and LinkedList with values in single line in Java.
Java 8 or earlier
List
List<String> strings = Arrays.asList("foo", "bar", "baz");
or if you already have an Array
String[] array = { "foo", "bar", "baz" };
List<String> strings = new LinkedList<>(Arrays.asList(array));
This will give you a List
which is backed by an Array. Note that this List
is immutable. That means if you try to add or remove any element from the List
, It will throw java.lang.UnsupportedOperationException
exception.
List
is mostly useful when you just want to populate a List and iterate it.
If you want to create a mutable List where you can add or remove elements. Initialize an ArrayList
or LinkedList
instead.
ArrayList
List<String> strings = new ArrayList<>(Arrays.asList("foo", "bar"));
strings.add("baz");
You can also use Collections.addAll()
static method to add values to ArrayList
List<String> strings = new ArrayList<String>();
Collections.addAll(strings,"foo", "bar", "baz");
Another way is to making an anonymous inner class with an instance initializer. This is also known as an double brace initialization. However that looks like an overkill to create a inner class just to create an ArrayList
.
List<String> strings = new ArrayList<String>() {
{
add("A");
add("B");
add("C");
}
};
LinkedList
LinkedList
can be initialized similarly as an ArrayList
using above three examples.
Java 9 or later
List.of()
is added in Java 9 which can be used to initialize a List
with values.
List<String> strings = List.of("foo", "bar", "baz");
With Java 10 or later, this can be even more shortened with the var
keyword.
var strings = List.of("foo", "bar", "baz");
Also we can define ArrayList
:
List<String> strings = new ArrayList<>(List.of("foo", "bar"));
strings.add("baz");
Using Streams
You can also use 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
:
List<String> strings = Stream.of("foo", "bar", "baz").collect(Collectors.toList());
Or you can even go from a String
to an ArrayList
:
List<String> strings = Stream.of("foo", "bar").collect(Collectors.toCollection(ArrayList::new));
strings.add("baz");