×

Java Programs

Java Practice

Java program to check a HashSet contains all elements of another HashSet

Java example to check a HashSet contains all elements of another HashSet.
Submitted by Nidhi, on May 09, 2022

Problem statement

In this program, we will create two sets using the HashSet collection to store integer elements. Then we will check a HashSet contains all elements of another HashSet using the containsAll() method.

Java program to check a HashSet contains all elements of another HashSet

The source code to check a HashSet contains all elements of another HashSet is given below. The given program is compiled and executed successfully.

// Java program to check a HashSet contains all elements 
// of another 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.containsAll(nums2))
      System.out.println("The set nums1 contains all elements of set nums2.");
    else
      System.out.println("The set nums1 does not contain all elements of set nums2.");

    if (nums1.containsAll(nums3))
      System.out.println("The set nums1 contains all elements of set nums3.");
    else
      System.out.println("The set nums1 does not contain all elements of set nums3.");
  }
}

Output

The set nums1 contains all elements of set nums2.
The set nums1 does not contain all elements of set nums3.

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. And, we created three sets nums1, nums2, and nums3 to store integer data elements using HashSet collection. Then we checked nums1 HashSet with nums2, and nums HashSets using the containsAll() method and printed the appropriate message. The containsAll() method is used to check a HashSet contains all elements of another HashSet.

Java HashSet Programs »





Comments and Discussions!

Load comments ↻





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