java 9 -

Java 9 : Convenience Factory methods List.of(), Set.of() and Map.of() for creating immutable collections

Java 9 added new static factory methods on the List, Set, and Map interfaces make it simpler to create immutable instances of those collections.

  • Set.of() for creating immutable Set
  • Map.of() for creating immutable Map
  • List.of() for creating immutable List

java 9 convenience factory methods for collections

Immutable Set using Set.of()

Creating a small immutable Collection in Java using the traditional way is very verbose. Let’s take an example of a Set:

//Immutable Set
Set<String> set = new HashSet<String>();
set = Collections.unmodifiableSet(set);

This can also be written as :

Set<String> set = Collections.unmodifiableSet(new HashSet<String>(){{

In place of this, Set.of() convenience method can be used in following manner :

//Immutable Set : Java 9
Set<String> set = Set.of("apple","banana","orange");


Immutable Map using Map.of()

//Unmodifiable Map : Java 9
Map<String,String> map = Map.of("key1","value1","key2","value2","key3","value3");

This creates an immutable Map similar to :

//Unmodifiable Map
Map<String,String> map = Collections.unmodifiableMap(new HashMap<String,String>(){{


Immutable List using List.of()

Along with Collections.unmodifiableList(), Java already provides a way of creating an immutable List using Arrays.asList():

List<String> list = Arrays.asList("apple","banana","orange");

We can also use the List.of() method added in Java 9 :

//Unmodifiable List : Java 9
List<String> list = List.of("apple","banana","orange");




© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags