簡體   English   中英

檢查兩個集合是否包含相同元素的方式,與訂單無關?

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

假設我有兩個不同的哈希集,如下所示,我如何檢查兩個哈希集包含相同的元素,這兩個哈希集是相等的,獨立於集合中元素的順序,請指教.. !!

Set set1=new HashSet();
          set.add(new Emp("Ram","Trainer",34000));
          set.add(new Emp("LalRam","Trainer",34000));

另一個是......

Set set2=new HashSet();
          set.add(new Emp("LalRam","Trainer",34000));
          set.add(new Emp("Ram","Trainer",34000));

員工pojo是......

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;

        }*/
} 

引自AbstractSet.equals(Object)的 javadoc:

如果給定對象也是一個集合,則返回true,兩個集合具有相同的大小,並且給定集合的每個成員都包含在此集合中。 這可確保equals方法在Set接口的不同實現中正常工作。

所以簡單地調用set1.equals(set2)就足夠了。 當且僅當集合包含相同的元素時,它才會返回true (假設您已在集合中的對象上正確定義了equalshashCode )。

使用以下表達式。

set1.containsAll(set2) && set2.containsAll(set1)

假設你已經定義了equals和hashcode,這是一種方法。 對大型會員來說效率不高。

  1. 檢查每個元素的數量。 如果他們不平等,你就完成了[不相等]。
  2. 循環通過Set1。 檢查Set2是否包含每個元素,如果不是,則完成[不相等]。 否則,如果你通過整套,你是平等的

更新:我不知道containsAll,這節省了很多麻煩,基本上做了算法

int s1 = set1.size();
int s2 = set2.size();
if (s1 !=s2) return false;
return set1.containsAll(set2);

如果你想要數據相等,那么正確地實現equals()hashCode()然后你可以使用Collection.containsAll(...) 當然,你需要確保只有當你的兩個集合都有相同數量的元素時才調用它,否則你可以說它們不相等。

做:

  setResult = set2.clone();

  if ( setResult.retainAll( set1 ) ){

   //do something with results, since the collection had differences

}

1 - 獲取一個集合(讓我們將它命名為“差異”),它將包含一個集合中的項目而另一個集合沒有 -

集合差異= CollectionUtils.subtract(Collection1,Collection2);

2 - 檢查尺寸== 0;

如果是這樣 - 兩個集合都有相同的元素; 如果不是 - 存在一些差異,那么你必須打印所有“差異”的項目。

不確定是否取決於物品訂單。 我正在以這種方式比較館藏

當您不知道集合的類型時,這是一個冗長但(希望)有效的解決方案:

public static <T> boolean equalIgnoreOrder(Collection<T> c1, Collection<T> c2) {
    int size1 = c1.size();  // O(1) for most implementations, but we cache for the exceptions.
    if (size1 != c2.size()) {
        return false;
    }
    Set<T> set;
    Collection<T> other;
    if (c1 instanceof Set) {
        set = (Set<T>) c1;
        other = c2;
    } else if (c2 instanceof Set) {
        set = (Set<T>) c2;
        other = c1;
    } else if (size1 < 12 ) { // N^2 operation OK for small N
        return c1.containsAll(c2);
    } else {
        set = new HashSet<>(c1);
        other = c2;
    }
    return set.containsAll(other);  // O(N) for sets
}

除非您出於某種原因需要實現自己的方法,否則只需使用h1.equals(h2) 下面描述可能的實現。

  1. 檢查元素的數量是否相同。 如果沒有,則返回false。
  2. 克隆設置2(如果你需要保持設置2之后)
  3. 迭代集合1,檢查是否在克隆集2中找到每個元素。如果找到,則從集合2中刪除。如果未找到,則返回false。
  4. 如果到達迭代的末尾並匹配集合1的每個元素,則集合相等(因為您已經比較了2個集合的大小)。

例:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM