Immutable collections with convenient factory methods

Many times we directly add or remove elements from a collection, which is returned from the factory method. This collection is immutable and adding items into these collection gives us an exception called UnSupportedOperationException.

To avoid such situations, we create immutable collection objects by using the collections.unmodifiableXXX() method. These methods are also tedious, such as writing multiple statements for adding individual items and then adding into it immutable List or Set or Map:

Before Java 9, List<String> asiaRegion = new ArrayList<String>();asiaRegion.add("India");asiaRegion.add("China");asiaRegion.add("SriLanka");List<String> unmodifiableAsiaRegionList = Collections.unmodifiableList(asiaRegion); ...

Get Java 9 Dependency Injection now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.