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]