With the Java 9 oracle introduced static overloaded methods called of() in Set, List and Map to handle immutable collection and map.
Earlier, to create immutable collection developers had to construct it by having one local variable and fill the elements using add
method and then by wrapping into Collections.unmodifiableSet( ).
Let us see the example by creating immutable set using unmodifiableSet method:
private Set immutableFruitSet() {
Set fruits = new HashSet<>();
names.add("Apple");
names.add("Banana");
names.add("Mango");
return Collections.unmodifiableSet(fruits);
}
Above code can be written simply as below using Java 9’s of() method which are avilable in Set, List and Map.
private Set<String> immutableFruitSet() {
return Set.of("Apple", "Banana", "Mango");
}
//We can get immutable Map as simple as below
return Map.of("Apple", 1, "Banana", 2,"Mango",3);
of() method will throw below exceptions
It throws IllegalArgumentException
if the elements are duplicates
and throws NullPointerException
if an element is null.
Facebook Comments