Java program to find the intersection of HashSet collections

Given a HashSet, we have to find the intersection.
Submitted by Nidhi, on May 11, 2022

Problem Solution:

In this program, we will create two sets using the HashSet collection to store integer elements. Then we will find the intersection of HashSet collections using the retainAll() method and assign the result to a new HashSet collection.

Program/Source Code:

The source code to find the intersection of HashSet collections is given below. The given program is compiled and executed successfully.

// 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]

Explanation:

In the above program, we imported the "java.util.*" package to use the HashSet collection. Here, we created a public class Main that contains a main() method.

The main() method is the entry point for the program. Here, we created two sets to store integer data elements using HashSet collection. Then we calculated the intersection of nums1, nums2 using retainAll() method.

The retainAll() method removes elements from a HashSet that are not contained in the specified HashSet.

Java HashSet Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.