Guava’s ImmutableSet Class in Java

In this post, we will talk about Guava’s ImmutableSet class in Java which has many static utility methods for creating Immutable Sets in Java.


 

1. ImmutableSet.of()

Guava’s ImmutableSet.of() returns an immutable set having the given elements. Guava provides seven overloaded versions of of() method, the last one with var-args for handling any number of elements as shown below:

 
static ImmutableSet of()
static ImmutableSet of(E element)
static ImmutableSet of(E e1, E e2)
static ImmutableSet of(E e1, E e2, E e3)
static ImmutableSet of(E e1, E e2, E e3, E e4)
static ImmutableSet of(E e1, E e2, E e3, E e4, E e5)
static ImmutableSet of(E e1, E e2, E e3, E e4, E e5, E e6, E... others)

 

Download   Run Code

 

2. Builder

Guava also provides a builder for creating ImmutableSet instances.

 

Download   Run Code

 

3. ImmutableSet.copyOf()

Guava’s ImmutableSet.copyOf() method returns an immutable set containing elements of the specified collection, a non-primitive array, or an iterator.

 

Download   Run Code

 

4. ImmutableSet.contains()

Guava’s ImmutableSet.contains() method finds if the target element is present in the immutable set or not.

 

Download   Run Code

 

5. ImmutableSet.iterator()

Guava’s ImmutableSet.iterator() method returns an unmodifiable iterator across Set’s elements.

 

Download   Run Code

 

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of