

The list returned by the unmodifiableList() method also doesn't support add, remove, or set operation and throws UnsupportedOperationException if you call them. ListOfString = Collections.unmodifiableList(listOfString) This is the same as the unmodifiable list you create in JDK 6 or 7 as shown below: How to create Immutable List, Set, and Map in Java 8 It not only covers the Collections but also other essential Java topics like threads, networking, and IO. If you are not familiar with the Java Collection framework then The Complete Java MasterClass course on Udemy is a good starting point. However, if the contained elements are themselves mutable, this may cause the Collection to behave inconsistently or its contents to appear to change.

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.Ĭalling any mutator method will always cause UnsupportedOperationException to be thrown. List list = List.of( "Java", "Kotlin", "Groovy") īut, the only catch is that you can create an unmodifiable or immutable List, Set, or Map. 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:

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. JDK has added static factory methods like of() on to basic Collection interfaces which you can use to create a list of items.Įven though the Project Jigsaw or Java Module systems is the main highlight of the Java 9 release, there are several other useful features that are more helpful from a development point of view e.g. 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. to create a list of 1, 2, 3 you can simply write val items = listOf(1, 2, 3). 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. The JEP stands for the JDK enhancement proposal. 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.
