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:
Listlist = Arrays.asList("Norway", "Denmark");
Using JDK7:
Listlist = new ArrayList<>(); list.add("Finland"); list.add("Norway");
Using JDK8:
Listlist = Stream.of("France", "Germany").collect(Collectors.toList());
Immutable list:
If we want to have an immutable list we can try the following:
ListimmutableList = 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:
ListmutableList = new ArrayList<>(List.of("Norway", "Finland", "Sweden"));
Source:
Initialize list in Java
Java doc list