javacodex.com
Java Examples
Java Examples
memu home questions

Calculate The Intersection Of Two Sets

The following java example shows how to calculate the intersection of two sets.

Source: (Intersection.java)

import java.util.*;
 
public class Intersection {
   public static void main(String args[]){
      HashSet<String> set1 = new HashSet<String>();
      set1.add("Tom");
      set1.add("Tim");
      set1.add("Amy");
      set1.add("Bob");
      set1.add("Paul");
 
      HashSet<String> set2 = new HashSet<String>();
      set2.add("Jeff");
      set2.add("Amy");
      set2.add("Paul");
      set2.add("Bill");
      set2.add("Mike");
 
      HashSet<String> intersection = new HashSet<String>(set1);
      intersection.retainAll(set2);
      System.out.println("Set1: " + set1);
      System.out.println("Set2: " + set2);
      System.out.println("Intersection: " + intersection);
   }
}
 

Output:

# java Intersection 
Set1: [Paul, Amy, Bob, Tom, Tim]
Set2: [Paul, Bill, Amy, Mike, Jeff]
Intersection: [Paul, Amy]

Contact: javacodex@yahoo.com