How to Create a List in Java


There are many ways to initialize lists in Java. Here, we’ll get an idea of how to create a new ArrayList.

Note that there are many different List implementations, each of which have their own benefits.

List a = new ArrayList();
List b = new LinkedList();
List c = new Vector(); 
List d = new Stack(); 
List e = new CopyOnWriteArrayList();

1. Empty, mutable list

new ArrayList<>();
Lists.newArrayList(); // Guava

2. Empty, immutable list

Collections.emptyList();
Collections.EMPTY_LIST;

3. Non-empty, mutable list

new ArrayList<>(Arrays.asList(1,2)); // Java 8
new ArrayList<>(List.of(1,2)); // Java 9
Lists.newArrayList(1, 2); // Guava

4. Non-empty, fixed size list

Arrays.asList(1,2); // Java 8
List.of(1,2); // Java 9
Lists.asList(1, 2); // Guava
Lists.asList(1, new int[] { 2, 3 }); // Guava
Ints.asList(new int[] { 1, 2, 3 }); // Guava

5. Non-empty, immutable list

Collections.unmodifiableList(Arrays.asList(1,2));
ImmutableList.of(1,2); // Guava
ImmutableList.of(Lists.newArrayList(1,2)); // Guava
ImmutableList.builder() // Guava
             .add(1)
             .add(2)
             .build();
Collections.singletonList(1); // Serializable