Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to check if two Collections contain the same elements, independent of order?

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;

        }*/
} 
like image 926
user1582269 Avatar asked Aug 09 '12 17:08

user1582269


2 Answers

Quoting from AbstractSet.equals(Object) javadoc:

Returns true if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface.

So it's sufficient to simply call set1.equals(set2). It will return true if and only if the set contain the same elements (assuming that you have correctly defined equals and hashCode on the objects in the sets).

like image 196
Petr Avatar answered Oct 20 '22 20:10

Petr


Use the below expression.

set1.containsAll(set2) && set2.containsAll(set1)
like image 10
Aaron Kurtzhals Avatar answered Oct 20 '22 22:10

Aaron Kurtzhals