Java 9 Convenience Factory Methods for Collections
Java 9 enhances the java collections and provides static methods for creating small immutable collection instances.
Before this feature creation of immutable collection was really verbose and required some line of codes.
How to do it before Java 9
List list = new ArrayList<>(); list.add(3); list.add(4); list.add(5); list = Collections.unmodifiableList(list); //or list = Collections.unmodifiableList(Arrays.asList(3, 4, 5)); //or using java 8 stream api list = Collections.unmodifiableList(Stream.of(3,4,5).collect(Collectors.toList()));
All these options involves various steps and unnecessary objects creation.
Java 9 comes with new static methods for List, Set and Map interfaces for creating immutable collections.
list = List.of(3, 4, 5);
There are overloaded
of methods with fixed-size argument lists and also varargs overload method, so that there is no limitation on collection size.
So in order to create immutable List and Map we can do the following:
Set set = Set.of(2, 4); Map<Integer, String> map = Map.of(1, "a", 2, "b");