In this article we will see another JDK 9 feature to create Immutable Collections. Till Java 8, If we want to create immutable collections we use to call unmodifiableXXX() methods on java.util.Collections class. For example, To create unmodifiable list, we should write below code.
The above code is too verbose to create a simple unmodifiable List. As Java is adopting functional programming style Java 9 came up with convenience, more compacted factory methods to create unmodifiable collections with JEP 269. Let us see how that works.
Create Empty List:
Create Non-Empty List:
Create Non-Empty Map:
If you look at the above Java 9 factory method, the code is simple one liner to create immutable collections. In the coming article we will see another Java 9 feature. Till then, Stay Tuned!!!
This post first appeared on Smart Techie | My Thoughts, My Work, My Ideas, please read the originial post: here