Google Guava is an open source library which provides lots of useful utility to Java programmer, one of them is easy way to find intersection and union of two Set in Java. You might have used Google Guava for other functionality e.g. for overriding toString in 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 couple of static method 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
Here is complete code example of How to calculate union and intersection of two Set in Java. It use's static method Sets.intersection() and Sets.union() to find intersection and union of two Sets in Java.
That's all on How to find Union and Intersection of two Set 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 open source library, you can write your own method to do the same thing, But as Joshua Bloch suggested in its popular book Effective Java, Use library method as much as possible. That's encourages me to explore more on Apache commons, Google Guava and Spring framework API more and more and I did find couple of gems like calculating time difference with Stopwatch in Spring framework which helps a lot.
Other Apache commons, Google Guava and Spring examples