Java Program to Remove Elements From a HashSet That Are Not Contained in a Specified HashSet

You are currently viewing Java Program to Remove Elements From a HashSet That Are Not Contained in a Specified HashSet

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

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

Ranjith

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

Leave a Reply