Create Java List with Initial Values

In this article, we’ll introduce various ways of creating List with initial values, at the time of its construction.

We’ll first introduce how to do it with Java built-in methods. Then we’ll also share how to do it with Google Guava.

Arrays.asList()

Arrays.asList() returns an ArrayList, but attention that the ArrayList here is different from java.util.ArrayList we normally used. The ArrayList returned by Array.asList() is of type java.util.Arrays.ArrayList, which means it is an inner class of java.util.Arrays.

java.util.Arrays.ArrayList extends java.util.AbstractList, which implements java.util.List.

  List<Integer> list1 = Arrays.asList(1,2,3,4,5);
  log.info("list 1: {}", list1); // 1,2,3,4,5

Elements in the list created by Arrays.asList() can be edited, for example:

  list1.set(0, 10);
  log.info("{}", list1); // 10,2,3,4,5

When we add elements to the list or remove elements from it, we will get UnsupportedOperationException. This is because the java.util.Arrays.ArrayList doesn’t implement add or remove method, java.util.Arrays.ArrayList behaves like a fixed array. If you are intrested in the implementation of Arrays.asList() and why it throw UnsupportedOperationException, please check this article.

 list1.remove(0); // throw UnsupportedOperationException
 list1.add(6); // throw UnsupportedOperationException

new ArrayList<>(Collection c)

new ArrayList<> accepts a collection to initialize the list, we can use off-the-shelf defined collection or Arrays.asList() as method parameters to create a new list.

  List<Integer> list2 = new ArrayList<>(list1);
  List<Integer> list2 = new ArrayList<>(Arrays.asList(1,2,3,4,5));

Anonymous Class

We can create a list object by creating an anonymous class of ArrayList, which calls add method internally in the static initialization section.

  List<Integer> list3 = new ArrayList<>() {{
    add(1);
    add(2);
  }}; 

Every time we create an object this way, we create an anonymous class, it is cost intensive, so avoid using this method when we need create objects very frequently.

Stream.of from JDK 8

  List<Integer> list5 = Stream.of(1,2,3,4,5).collect(Collectors.toList());

List.of() from JDK 9

If we’ve already migrated to JDK9, we can simply use collection factory methods.

  List<Integer> list6 = List.of(1,2,3,4,5);  

The list returned by List.of() is unmodifiable, we cannot add new value to the list, we cannot remove values from the list, nor can we change the value of list elements.

Lists.newArrayList from Google Guava

If we have Google Guava library in our classpath, we can simply use Lists.newArrayList, this is the most preferred way I personally recommend.

  List<Integer> list6 = Lists.newArrayList(1,2,3,4,5);

We can get an immutable version list by using ImmutableList.of.

 List<Integer> list7 = ImmutableList.of(1,2,3,4,5);

Read More