How to initialize List of String or List in Java?

In Java, the List<E> is an interface. As it is an interface that means it cannot be instantiated (no new List() is possible). The class needs to implement that interface. Following are all the known implementing classes:

  • AbstractList
  • AbstractSequentialList
  • ArrayList
  • AttributeList
  • CopyOnWriteArrayList
  • LinkedList
  • RoleList
  • RoleUnresolvedList
  • Stack
  • Vector

There are multiple ways we can initialize a List of String. The approaches are discussed below:

Using JDK2:

List list = Arrays.asList("Norway", "Denmark");

Using JDK7:

List list = new ArrayList<>();
list.add("Finland");
list.add("Norway");

Using JDK8:

List list = Stream.of("France", "Germany").collect(Collectors.toList());

Immutable list:

If we want to have an immutable list we can try the following:

List immutableList = List.of("Norway", "Finland", "Sweden");

Mutable list:

If we want to use List.of but want to have a mutable list we can try the following:

List mutableList = new ArrayList<>(List.of("Norway", "Finland", "Sweden"));

Source:
Initialize list in Java
Java doc list

Share