Initialize Java list
In this article, we will take a look at different ways to initialize a list in one line containing elements with examples.
java.util.Arrays
has a static asList()
method which accepts an array and returns a list with the elements of this array.You can provide an array or a series of elements separated by a comma. Example,
List<String> letters = Arrays.asList("A", "B"); List<Integer> numbers = Arrays.asList(new Integer[]{1,2});
The list is backed by the array, which means that any changes made to the list will also be visible in the array and vice-versa. Example,
String[] letters = { "A", "B" }; List<String> list = Arrays.asList(letters); list.set(0, "C"); System.out.println("Modified array:" + Arrays.toString(letters)); letters[0] = "D"; System.out.println("Modified list:" + list);
Output is
Modified array:[C, B] Modified list:[D, B]
As you can see, modifying the list also modifies the array and vice-versa.
Note that you cannot modify the size of list created with Arrays.asList()
. That is, you cannot call add()
or remove()
method on it.
Doing so would result in UnsupportedOperationException. Example,
List<String> list = Arrays.asList("A", "B"); list.add("C");
Result will be
Exception in thread “main” java.lang.UnsupportedOperationException
at java.base/java.util.AbstractList.add(AbstractList.java:153)
at java.base/java.util.AbstractList.add(AbstractList.java:111)
Java 8 stream provides a static
of()
method, which takes a var-args as parameter and returns a stream of those elements.This stream can be converted to a list using
collect()
and Collectors.toList()
method as shown below
List<String> letters = Stream.of("A", "B"). collect(Collectors.toList()); letters.add("C"); System.out.println(letters);
You can add and remove elements from this list.
3. Java 9 of() method
In java 9, of()
method was added to List interface, which accepts multiple arguments and returns a list with those elements.
of()
is a static interface method. Example,
List<String> letters = List.of("A", "B");
List returned by of()
is an unmodifiable list, meaning that you cannot add or remove elements from it.