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.
The what
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: List.of()
, Set.of()
and Map.of()
. It's a nice and light-weight way to make collections with predefined elements.
The how
As of Java 9, we can do the following for a List
:
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
:
Set.of(1, 2, 3);
Note that Set
doesn't provide any ordering guarantees.
And Map
, with ofcourse keys and values:
Map.of("1", 1, "2", 2, "3", 3);
Also good-to-know
null
values
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 null
values.
Immutable
All created collections are immutable. If you try to add a new element, you'll get a UnsupportedOperationException
.