Write a program to compare two hashsets in Java.
HashSet is one of a data structures in the Java Collections API. It stores unique elements and permits nulls.It's backed by a HashMap.It doesn't maintain insertion order. And it's not thread-safe.
Let us write a function to create a HashSet with n elements and return it.
HashSet<string> createSet(int n){
System.out.println("Enter the set elements");
HashSet<string>set = new HashSet<string>();
for(int i=0;i<n;i++){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string");
String str = scanner.nextLine();
if(set.add(str)==false){
System.out.println("Not able to add the string to set");
}
}
return set;
}
We create a Hashset using its constructor - in this example we have a set of Strings - hence new HashSet<String>() Then we add elements to it using add() method. The method returns boolean - true if successful, false if not. If the value is already present, add() method fails.
Next we need to compare two sets. One easy way of doing it will be - iterate over all the elements of first set and find it that element is present in the second set.
boolean compareSets(HashSet<string> s1,HashSet<string> s2){
for(String str:s1){
if(s2.contains(str))
continue;
return false;
}
return true;
}
We are using for each loop. For each string str in set s1, find if set s2 contains str. If it does, move to next element. If not return false. And if each element of s1 is present in s2, then return true.
Another method would be to use containsAll().
if(set1.size()==set2.size() && set1.containsAll(set2))
System.out.println("The two sets are same");
Let us look at the complete program.
import java.util.HashSet; import java.util.Scanner; public class SetDemo { static HashSet<String> createSet(int n){ System.out.println("Enter the set elements"); HashSet set = new HashSet<String>(); for(int i=0;i<n;i++){ Scanner scanner = new Scanner(System.in); System.out.println("Enter a string"); String str = scanner.nextLine(); if(set.add(str)==false){ System.out.println("Not able to add the string to set"); } } return set; } static boolean compareSets(HashSet<String> s1,HashSet<String> s2){ for(String str:s1){ if(s2.contains(str)) continue; return false; } return true; } public static void main(String args[]){ HashSet<String> set1 = createSet(5); HashSet<String> set2 =createSet(5); if(set1.size()==set2.size() && compareSets(set1,set2)==true){ System.out.println("sets are same"); }else{ System.out.println("sets are not same"); } } }
Comments
Post a Comment