Check whether two HashSet are equal in Java


At first, create the first HashSet and add elements to it −

// create hash set 1
HashSet hs1 = new HashSet();
hs1.add("G");
hs1.add("H");
hs1.add("I");
hs1.add("J");
hs1.add("K");

Create the second HashSet and add elements to it −

// create hash set 2
HashSet hs2 = new HashSet();
hs2.add("G");
hs2.add("H");
hs2.add("I");
hs2.add("J");
hs2.add("K");

To check whether both the HashSet are equal or not, use the equals() method −

hs1.equals(hs2)

The following is an example to check whether two HashSet are equal −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // create hash set 1
      HashSet hs1 = new HashSet();
      hs1.add("G");
      hs1.add("H");
      hs1.add("I");
      hs1.add("J");
      hs1.add("K");
      System.out.println("Elements in set 1 = "+hs1);
      // create hash set 2
      HashSet hs2 = new HashSet();
      hs2.add("G");
      hs2.add("H");
      hs2.add("I");
      hs2.add("J");
      hs2.add("K");
      System.out.println("Elements in set 2 = "+hs2);
      System.out.println("Are both the HashSet equal? "+hs1.equals(hs2));
   }
}

Output

Elements in set 1 = [G, H, I, J, K]
Elements in set 2 = [G, H, I, J, K]
Are both the HashSet equal? True

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements