This article will discuss Sets class by Guava in Java.

The Sets class by Guava is a Java library that provides several static utility methods for working with sets. It can help we create, manipulate, and perform operations on sets in a convenient and efficient way. To use the Guava Sets class, we need to import the com.google.common.collect.Sets package. Some of the methods that the Sets class offers are:

1. Using Sets.newHashSet() method

Guava library provides the Sets.newHashSet() method is a convenient way to create a mutable HashSet instance in Java. It returns a mutable HashSet instance containing distinct elements from the specified array, iterable or iterator as the argument. Guava also has Sets.newConcurrentHashSet() method, which returns a thread-safe Set backed by a HashMap. Here’s an example of using these methods:

Download Code

2. Using Sets.newTreeSet() method

To create a TreeSet instance, Guava provides the Sets.newTreeSet() method that sorts by the natural sort ordering of its elements or with the given comparator. The TreeSet can be initialized with the elements of an iterable. Guava also provides Sets.newLinkedHashSet() method that creates a mutable LinkedHashSet instance. Here’s an example of using these methods:

Download Code

3. Using Sets.filter() method

The 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. Here’s an example:

Download Code

4. Using Sets.difference() method

The Guava Sets.difference() method returns an unmodifiable view of the two sets’ difference. The returned set contains all elements that are present in the first set and not present in the second set. Guava also has Sets.symmetricDifference() method, which gives a view that cannot be modified and shows the elements that are in one set or the other, but not both. Here’s an example of using these methods:

Download Code

5. Using Sets.intersection() method

The Guava 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. Here is an example of using this method:

Download Code

6. Using Sets.union() method

The Guava 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. Here’s an example:

Download Code

7. Using Sets.powerSet() method

The Guava Sets.powerSet() method returns the set of all possible subsets of a set. A power set of a set S is the set of all possible subsets of S, including the empty set and S itself. Here is an example of using this method:

Download Code

Output:

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

That’s all about Sets class by Guava in Java.