java 9 - topjavatutorial.com

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.add("apple");
set.add("banana");
set.add("orange");
set = Collections.unmodifiableSet(set);

This can also be written as :

Set<String> set = Collections.unmodifiableSet(new HashSet<String>(){{
  add("apple");
  add("banana");
  add("orange");
}});

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>(){{
  put("key1","value1");
  put("key2","value2");
  put("key3","value3");
}});

 

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");

 

Reference

 

© 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