Way to check if two Collections contain the same elements, independent of order?
collections, hashset, java
Solution
Unless you need to implement your own method for some reason, just use `h1.equals(h2)`. A possible implementation is described below.
- Check if # of elements is the same. If not, return false.
- Clone set 2 (if you need to keep set 2 after)
- Iterate through set 1, check if each element is found in clone set 2. If found, remove from set 2. If not found, return false.
- If you reach the end of the iterations and have matched each element of set 1, the sets are equal (since you already compared the sizes of the 2 sets).
Example:
public boolean isIdenticalHashSet <A> (HashSet h1, HashSet h2) {
if ( h1.size() != h2.size() ) {
return false;
}
HashSet<A> clone = new HashSet<A>(h2); // just use h2 if you don't need to save the original h2
Iterator it = h1.iterator();
while (it.hasNext() ){
A = it.next();
if (clone.contains(A)){ // replace clone with h2 if not concerned with saving data from h2
clone.remove(A);
} else {
return false;
}
}
return true; // will only return true if sets are equal
}
Problem
Let say I have two different hashsets as shown below how can I check that two Hashset contain the same elements and these two hashsets are equal, independent of the order of elements in collection, please advise..!! ``` Set set1=new HashSet(); set.add(new Emp("Ram","Trainer",34000)); set.add(new Emp("LalRam","Trainer",34000)); ``` and the other one is .. ``` Set set2=new HashSet(); set.add(new Emp("LalRam","Trainer",34000)); set.add(new Emp("Ram","Trainer",34000)); ``` The employee pojo is ... ``` class Emp //implements Comparable { String name,job; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } int salary; public Emp(String n,String j,int sal) { name=n; job=j; salary=sal; } public void display() { System.out.println(name+"\t"+job+"\t"+salary); } public boolean equals(Object o) { Emp p=(Emp)o; return this.name.equals(p.name)&&this.job.equals(p.job) &&this.salary==p.salary; } public int hashCode() { return name.hashCode()+job.hashCode()+salary; } /* public int compareTo(Object o) { Emp e=(Emp)o; return this.name.compareTo(e.name); //return this.job.compareTo(e.job); // return this.salary-e.salary; }*/ } ```