In this tutorial we will check how we can initialize list with values in one line.
Assume we have some objects (in our example just String literals) and want to gather them in the list;
Initializing from array
Starting from Java 6, we have only one method – using constructor taking an array, which is created via java.util.Arrays class:
List<String> list = Arrays.asList("a", "b");
Please be aware, that such method of initialization will create a list backing array (see array-backed-list for details). It’s good when the list will be read only or there won’t be modification of list’s length.
If we want to have normal list, we have to repack returned list in this way:
List<String> list = new ArrayList(Arrays.asList("a", "b"));
This kind of initialization have some performance issues – it creates array, then list backing array and finally another list, which contains all object references.
Please note this fact, when your memory or performance issues are important factors.
Initializing from stream
Java 8 introduced stream api, which also provides one liner returning initialized list:
List list = Stream.of("a", "b").collect(Collectors.toList());
We can’t be sure about the type of returned list, so we shoudn’t rely on any implementation.
Again, this solution has higher performance cost than use of Arrays.asList().
Initializing from factory method
With Java 9, we can make use of factory method:
List list = List.of("a", "b");
In this case the returned list is immutable, throwing java.lang.UnsupportedOperationException in case of modification (adding, removing, etc).
Initializing with third party libraries
There are some libraries, which simplify or extend use of Java Collections. Lets see some examples:
With Google Guava:
List list = Lists.newArrayList("a", "b");
With Eclipse Collections:
List list = Lists.mutable.with("a", "b");