Java Program to Find the Intersection of HashSet Collections

Java program to find the intersection of HashSet collections

// Java program to find the intersection of 
// HashSet collections

import java.util.*;

public class Main {
  public static void main(String[] args) {
    HashSet < Integer > nums1 = new HashSet();
    HashSet < Integer > nums2 = new HashSet();

    nums1.add(1);
    nums1.add(2);
    nums1.add(3);
    nums1.add(4);
    nums1.add(5);
    nums1.add(6);

    nums2.add(1);
    nums2.add(2);
    nums2.add(3);
    nums2.add(4);
    nums2.add(7);
    nums2.add(8);

    System.out.println("Elements of nums1 set are: " + nums1);
    System.out.println("Elements of nums2 set are: " + nums2);

    HashSet < Integer > intersection = new HashSet < Integer > (nums1);
    intersection.retainAll(nums2);

    System.out.print("Intersection of nums1 and nums2: " + intersection);
  }
}

Output

Elements of nums1 set are: [1, 2, 3, 4, 5, 6]
Elements of nums2 set are: [1, 2, 3, 4, 7, 8]
Intersection of nums1 and nums2: [1, 2, 3, 4]
Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment