Fork me on GitHub

Programming, Internet & more

Java 9 Collection Initializer

Finally, after 3 years of waiting Java 9 has reached the world. This major release was delayed several times due to the integration of its famous modularization feature called “Project Jigsaw”. But besides that major feature, Java 9 contains several other minor improvements which make the life of a programmer easier but are not that popular.

Today, I would like to introduce the collection initializer feature.

Collection initializer

From time to time everyone has to initialize a collection of something. The typical Java way to do this was not very elegant compared to other programming languages. The most common way was to create a new collection and afterwards adding all the elements to it.

List<String> oldList = new ArrayList<>();
oldList.add("list");
oldList.add("initializer");
oldList.add("classic");
oldList.add("style");

There were a few other ways to initialize collections but none was as elegant as the new collection initializer feature. With Java 9 it is possible to do the initialization in one line as we know it from other languages.

List<String> newList = List.of("list", "initializer", "java 9", "style");

One important thing to notice is that the new “of” method does not return one of the common list implementations like ArrayList. Instead, a new immutable list implementation is used, which is not available in the public API. This means you cannot add or remove an item in the list. Doing this will result in an UnsupportedOperationException.

newList.add("boom"); // UnsupportedOperationException
newList.remove(0); // UnsupportedOperationException
newList.clear(); // UnsupportedOperationException

The “of” method can also be applied to the collection types Map and Set.

Set<String> set = Set.of("set", "initializer", "java 9", "style");
Map<Integer, String> map = Map.of(1, "map", 2, "initializer");

Conclusion

After so many years of waiting it was about time that we also got a simple way to initialize collections. There are some drawbacks, like immutability, but I think it was a reasonable decision to design it like that in regard to performance aspects.

Category: java9

Leave a Reply

Your email address will not be published. Required fields are marked *