New in Java 9: Collection Factory Methods
One of the nice new things in Java 9 are Collection Factory Methods. In this article, I'll tell you about these new methods.
If you have a small collection, with predefined elements, you usually do something like the following:
List<String> languages = new ArrayList<>(); newEmployees.add("Dutch"); newEmployees.add("English"); newEmployees.add("German");
While above code perfectly works, I think we can agree that it doesn't look that pretty. Firstly, we have to think about the implementation type we want to use for the
List. Secondly, we need three statements to add an element and one to create a
List. It's hard to do this as a field initializer in a class. All in all, it could be better.
Luckly, as of Java 9, it's actually better. We got Collection Factory Methods:
Map.of(). It's a nice and light-weight way to make collections with predefined elements.
As of Java 9, we can do the following for a
List<String> languages.of("Dutch", "English", "German");
The method uses the best implementation of
List for you, so you don't have to think about that.
The same applies for
Set.of(1, 2, 3);
Set doesn't provide any ordering guarantees.
Map, with ofcourse keys and values:
Map.of("1", 1, "2", 2, "3", 3);
If you would try to add an element that is
null to a collection:
List.of(1, 2, null);
You'll get a
NullPointerException. It's simply not allowed to add
All created collections are immutable. If you try to add a new element, you'll get a