Guava’s Sets Class in Java

In this article, we will talk about Guava Sets class which provides several static utility methods pertaining to Set instances.

 

1. Sets.newHashSet()

Guava library provides Sets.newHashSet() method that returns a mutable HashSet instance containing distinct elements from the specified array, iterable or iterator.

 

Download   Run Code

Output:

[]
[1, 2, 3]
[1, 2, 3, 4, 5]

 

Guava also has Sets.newConcurrentHashSet() method which returns a thread-safe Set backed by a HashMap.

 

2. Sets.newTreeSet()

To create a TreeSet instance, Guava provides Sets.newTreeSet() method that sorts by the natural sort ordering of its elements or with the given comparator. The TreeSet can be initalized with the elements of an iterable.

 

Download   Run Code

Output:

[]
[1, 2, 3, 4]
[4, 3, 2, 1]

 

Guava also provides Sets.newLinkedHashSet() method that creates a mutable LinkedHashSet instance.

 

3. Sets.filter()

Guava Sets.filter() method returns a Set containing elements of the specified Set which satisfies a predicate. Any changes made to the returned Set affects the original Set and vice-versa.

 

Download   Run Code

Output:

[1, 3, 5]

 

4. Sets.difference()

Guava Sets.difference() method returns an unmodifiable view of the difference of two sets. The returned set contains all elements that are present in the first set and not present in the second set.

 

Download   Run Code

Output:

[2, 4, 6, 8]

 

5. Sets.intersection()

Guava’s Sets.intersection() method returns an unmodifiable view of the intersection of two sets. The returned set contains all elements that are present in both sets.

 

Download   Run Code

Output:

[3, 5]

 

6. Sets.union()

Guava’s Sets.union() method returns an unmodifiable view of the union of two sets. The returned set contains all elements that are present in either set.

 

Download   Run Code

Output:

[1, 2, 4, 5, 6, 3, 7]

 

7. Sets.powerSet()

Guava’s Sets.powerSet() method returns the set of all possible subsets of set.

 

Download   Run Code

Output:

[]
[1]
[2]
[1, 2]
[3]
[1, 3]
[2, 3]
[1, 2, 3]

 

 
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