Sunday, June 4, 2023

How to Union and Intersection of two Set in Java - Google Guava Example

To perform union and intersection operations on two sets in Java using Google Guava, you can utilize the Sets.union() and Sets.intersection() methods provided by the Guava library. 

Here's an example:


import com.google.common.collect.Sets;
import java.util.HashSet;
import java.util.Set;

public class SetOperationsExample {
    public static void main(String[] args) {
        // Creating two sets
        Set set1 = new HashSet<>();
        Set set2 = new HashSet<>();

        // Adding elements to set1
        set1.add(1);
        set1.add(2);
        set1.add(3);

        // Adding elements to set2
        set2.add(2);
        set2.add(3);
        set2.add(4);

        // Performing union operation using Guava's Sets.union()
        Set union = Sets.union(set1, set2);
        System.out.println("Union: " + union);

        // Performing intersection operation using Guava's Sets.intersection()
        Set intersection = Sets.intersection(set1, set2);
        System.out.println("Intersection: " + intersection);
    }
}


In this example, we create two sets set1 and set2 using the HashSet class. We add elements to both sets. Then, we use Sets.union(set1, set2) to perform the union operation and Sets.intersection(set1, set2) to perform the intersection operation. 

The results are stored in the union and intersection sets, respectively. 

Finally, we print the results. Make sure you have the Guava library added to your project's dependencies for this code to work.

No comments:

Post a Comment