Hello guys, this is my first article in Java 9 features on this blog and today you’ll learn about my favorite feature “factory methods for collection”, which is introduced as part of JEP 269. The JEP stands for JDK enhancement proposal. If you have worked in Groovy or Kotlin then you know that how easy is to create the list with elements using collection literals e.g. to create a list of 1, 2, 3 you can simply write val items = listOf(1, 2, 3). Unfortunately, Java doesn’t support that yet but things have been improved with the factory methods for collection in JDK 9 and it’s almost like that. JDK has added static factory methods like of() on to basic Collection interfaces which you can use to create a list of items.
Even though the Project Jigsaw or Java Module systems is the main highlight of Java 9 release, there are several other useful features which are more helpful from development point of view e.g. process API enchantment, Stream API enhancements and some useful methods on Optional class, but the API change which I liked most is the factory methods for Collection.
It allows you to create a list, set, and a map of values in just one line, just like you can do in Kotlin, Scala, or Groovy:
List<String> list = List.of("Java", "Kotlin", "Groovy");But, only catch is that you can create an unmodifiable or immutable List, Set, or Map.
The List, Set or Map returned by the of() static factory method are structurally immutable, which means you cannot add, remove, or change elements once added.
Calling any mutator method will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the Collection to behave inconsistently or its contents to appear to change.
Javin PaulFebruary 6th, 2018Last Updated: February 6th, 2018

This site uses Akismet to reduce spam. Learn how your comment data is processed.