Java program to remove elements from a HashSet that are not contained in a specified HashSet

Given a HashSet collection, we have to remove elements that are not contained in a specified HashSet.
Submitted by Nidhi, on May 10, 2022

Problem Solution:

In this program, we will create two sets using the HashSet collection to store integer elements. Then we will remove elements from a HashSet that are not contained in the specified HashSet using the retainAll() method.

Program/Source Code:

The source code to remove elements from a HashSet that are not contained in the specified HashSet is given below. The given program is compiled and executed successfully.

// Java program to remove elements from a HashSet that are not 
// contained in a specified HashSet

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);

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

    if (nums1.retainAll(nums2))
      System.out.println("\nRemoved items from nums1 set that are not contained in nums2.");
    else
      System.out.println("\nUnable to remove items from nums1 set.");

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

Output:

Elements of nums1 set are: [1, 2, 3, 4, 5, 6]
Elements of nums2 set are: [1, 2, 3, 4]

Removed items from nums1 set that are not contained in nums2.

Elements of nums1 set are: [1, 2, 3, 4]
Elements of nums2 set are: [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 nums1, nums2 to store integer data elements using HashSet collection. Then we added some elements to all sets using add() method. After that, we removed items from the nums1 set that are not contained in nums2.

The retainAll() method returns true on successful removal of a specified item, otherwise, it returns false.

Java HashSet Programs »






Comments and Discussions!

Load comments ↻






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