web
 

Java SE 9: Factory Methods for Immutable Set


Introduction

Oracle Corporation is going to release Java New Version: Java SE 9 around March 2017. So, I would like to deliver a series of Posts on Java SE 9 New Features. It is my sixth post in this series.

Java SE 8: Immutable Empty Set

In Java SE 8 and earlier Versions, if we want to create an empty Immutable or Unmodifiable Set, we should use Collections class utility method: unmodifiableSet as shown below:

Empty Set Example:-


 Set<String> emptySet = new HashSet<>();
 Set<String> immutableSet = Collections.unmodifiableSet(emptySet);

Here we can observe that it is very tedious and verbose process. Let us see the same thing in Java SE 9 now.

Empty Set API Utility

Copy
static <E> Set<E> of()

It is used to create an empty Immutable Set (a Set with zero elements).

Empty Set Example:-

Copy
Set<String> immutableSet = Set.of();

Here we can observe that it is very easy to create an empty Immutable Set in Java SE 9.

Java SE 8: Immutable Non-Empty Set

In this section, we will see how to create Immutable Non-Empty Set in Java SE 8 and earlier Versions. We use same unmodifiableSet method from Collections class to create an Immutable Non-Empty Set as shown below:

Non-Empty Set Example:-


 Set<String> nonemptySet = new HashSet<>();
 nonemptySet.add("one");
 nonemptySet.add("two");
 nonemptySet.add("three");
 Set<String> immutableSet = Collections.unmodifiableSet(nonemptySet);

Java SE 9: Immutable Non-Empty Set With Var-Args

Oracle Corp has introduced one more Set.of() method with Var-args syntax. The following is a Var-Args method (Variable Number of arguments method) used to create an Non-empty Immutable Set in Java SE 9:


static <E> Set<E> of(E... elements)  

It is used to create an Immutable Set with array of elements as shown below:

Non-Empty Set Example:-


 String[] nameArr =  { "one", "two", "three"};
 Set<String[]> set= Set.<String[]>of(nameArr);

Test this with Java SE 9 REPL:


jshell> String[] nameArr =  { "one", "two", "three"}
nameArr ==> String[3] { "one", "two", "three" }

jshell> Set<String[]> set = Set.<String[]>of(nameArr);
set ==> [[Ljava.lang.String;@56ef9176]

jshell> set
set ==> [[Ljava.lang.String;@56ef9176]

Here we have created an Immutable Set with Array of String Elements.






journaldev is optimized for learning.© journaldev .
All Right Reserved and you agree to have read and accepted our term and condition