×

Java Programs

Java Practice

Java program to remove HashSet elements contained in other HashSet

Java example to remove HashSet elements contained in other HashSet.
Submitted by Nidhi, on May 10, 2022

Problem statement

In this program, we will create 3 sets using the HashSet collection to store integer elements. Then we will remove elements of a HashSet from another HashSet using the removeAll() method.

Source Code

The source code to remove HashSet elements contained in other HashSet is given below. The given program is compiled and executed successfully.

// Java program to remove HashSet elements 
// contained in other HashSet

import java.util.*;

public class Main {
  public static void main(String[] args) {
    HashSet < Integer > nums1 = new HashSet();
    HashSet < Integer > nums2 = new HashSet();
    HashSet < Integer > nums3 = 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);

    nums3.add(10);
    nums3.add(20);
    nums3.add(30);
    nums3.add(40);

    if (nums1.removeAll(nums2))
      System.out.println("Removed items of nums2 set contained in nums1 set.");
    else
      System.out.println("Unable to remove items from nums1 set.");

    if (nums1.removeAll(nums3))
      System.out.println("Removed items of nums3 set contained in nums1 set.");
    else
      System.out.println("Unable to remove items from nums1 set.");

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

Output

Removed items of nums2 set contained in nums1 set.
Unable to remove items from nums1 set.
Elements of nums1 set are: [5, 6]
Elements of nums2 set are: [1, 2, 3, 4]
Elements of nums3 set are: [20, 40, 10, 30]

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 three sets nums1, nums2, nums3 to store integer data elements using HashSet collection. Then we added some elements to all sets using add() method. After that, we removed items of the nums2 set from the nums1 set using the removeAll() method.

The removeAll() 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.