×

Java Programs

Java Practice

Java program to check the HashSet collections have similar elements

Given a HashSet, we have to check whether it have similar elements.
Submitted by Nidhi, on May 11, 2022

Problem statement

In this program, we will create three sets using the HashSet collection to store integer elements. Then we will check HashSet collections have similar elements using the equals() method and print the appropriate message.

Java program to check the HashSet collections have similar elements

The source code to check the HashSet collection has similar elements, which is given below. The given program is compiled and executed successfully.

// Java program to check the HashSet collection 
// has similar elements

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);
    nums2.add(5);
    nums2.add(6);

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

    if (nums1.equals(nums2))
      System.out.println("HashSets nums1 and nums2 have similar elements.");
    else
      System.out.println("HashSets nums1 and nums2 does not have similar elements.");

    if (nums1.equals(nums3))
      System.out.println("HashSets nums1 and nums3 have similar elements.");
    else
      System.out.println("HashSets nums1 and nums3 do not have similar elements.");
  }
}

Output

HashSets nums1 and nums2 have similar elements.
HashSets nums1 and nums3 do not have similar elements.

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 to store integer data elements using HashSet collection. Then we checked HashSet collections to have similar elements using the equals() method and printed the appropriate message.

Java HashSet Programs »





Comments and Discussions!

Load comments ↻





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