Creating immutable collections using the of() and copyOf() factory methods
In this recipe, we will revisit traditionalmethods of creating collections and compare them with the List.of()
, Set.of()
, Map.of()
, and Map.ofEntries()
factory methods that came with Java 9, and the List.copyOf()
, Set.copyOf()
, and Map.copyOf()
methods that came with Java 10.
Getting ready
Before Java 9, there were several ways to create collections. Here is the most popular way that was used to create a List
:
List<String> list = new ArrayList<>(); list.add("This "); list.add("is "); list.add("built "); list.add("by "); list.add("list.add()"); list.forEach(System.out::print);
If we run the preceding code, we get this:
The shorter way of creating the List
collection is by starting with an array:
Arrays.asList("This ", "is ", "created ", "by ", "Arrays.asList()").forEach(System.out::print);
The result is as follows:
The Set
collection used to be created similarly:
Set<String> set = new HashSet...