Tuesday, August 17, 2021

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

Google Guava is an open-source library that provides lots of useful utility to Java programmers,  one of them is an easy way to find the intersection and union of two Sets in Java. You might have used Google Guava for other functionality e.g. for overriding toString in an easy way or Immutable Collection provided by Guava library. Along with Apache commons and Spring, Google Guava is a library you definitely want to include in your Project. Guava provides a couple of static methods to operate on Set in Java on package com.google.common.collect.Sets.

 There are two methods called intersection() and union() which provides intersection and union of two Sets in Java. In this example, we have used HashSet as Set implementation but it will work with any Set implementation e.g. TreeSet or LinkedHashSet.


How to find Intersection and Union of two Set in Java

How to calculate Intersection and union of Sets in JavaHere is a complete code example of How to calculate union and intersection of two Sets in Java. It use's static method Sets.intersection() and Sets.union() to find intersection and union of two Sets in Java.


package test;

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

/**
 *
 * Java program to demonstrate How to calculate Intersection and Union of two
 * Set using Google's Guava library example.
 *
 * @author http://javarevisited.blogspot.com.au
 */

public class SetIntersectionExample {

 
    public static void main(String args[]) {
 
        // Set which stores some Singer
        Set<String> singers = new HashSet<String>();
        singers.add("Amitabh Bacchan");
        singers.add("Shan");
        singers.add("Medona");
     
        // Another Set which stores Actors
        Set<String> actors = new HashSet<String>();
        actors.add("Amitabh Bacchan");
        actors.add("tom cruise");
        actors.add("SRK");
     
        // Calculating Intersection of two Set in Java
        Set<String> intersection = Sets.intersection(actors, singers);
        System.out.printf("Intersection of two Set %s and %s in Java is %s %n",
                singers.toString(), actors.toString(), intersection.toString());
        System.err.println("Number of elements common in two Set : "
                           + intersection.size());
     
        // Calculating Union of two Set in Java
        Set<String> union = Sets.union(actors, singers);
        System.out.printf("Union of two Set %s and %s in Java is %s %n",
                singers.toString(), actors.toString(), union.toString());
        System.out.println("total number of element in union of two Set is : "
                            + union.size());
    }
     
}

Output:
Intersection of two Set [Medona, Shan, Amitabh Bacchan] and [SRK, tom cruise, Amitabh Bacchan] in Java is [Amitabh Bacchan]

Number of elements common in two Set : 1
Union of two Set [Medona, Shan, Amitabh Bacchan] and [SRK, tom cruise, Amitabh Bacchan] in Java is [SRK, tom cruise, Amitabh Bacchan, Medona, Shan]

The total number of elements in the union of two Set is : 5


That's all on How to find the Union and Intersection of two Sets in Java. It's very simple if you are using right open-source library e.g. Google's Guava Collection. If you don't like to use the open-source library, you can write your own method to do the same thing, But as Joshua Bloch suggested in his popular book Effective Java, Use the library method as much as possible. 

That's encouraged me to explore more on Apache Commons, Google Guava, and Spring framework API more and more and I did find a couple of gems like calculating time difference with Stopwatch in Spring framework which helps a lot.



Other Java Collection tutorials you may like
  • How to sort a Map by keys and values in Java? (tutorial)
  • How to sort an ArrayList in ascending and descending order in Java? (tutorial)
  • Difference between ArrayList and HashSet in Java? (answer)
  • The difference between TreeMap and TreeSet in Java? (answer)
  • The difference between HashMap and ConcurrentHashMap in Java? (answer)
  • The difference between HashMap and LinkedHashMap in Java? (answer)
  • The difference between Hashtable and HashMap in Java? (answer)
  • The difference between HashSet and TreeSet in Java? (answer)
  • The difference between ArrayList and LinkedList in Java? (answer)
  • The difference between Vector and ArrayList in Java? (answer)
  • Difference between EnumMap and HashMap in Java

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment.

2 comments :

Anonymous said...

We can use addAll() and retainAll() methods of List and Set for this.

Anonymous said...

allAll() and retainAll() methods also modify the collection. These fucntions do not

Post a Comment