Java Collection Compare compareSet(Collection s1, Collection s2)

Here you can find the source of compareSet(Collection s1, Collection s2)

Description

Compares two sets of Objects.

License

Open Source License

Return

true if the sets compare equal, false otherwise.

Declaration


public static boolean compareSet(Collection s1, Collection s2) 

Method Source Code

//package com.java2s;
/**********************************************************************
 Copyright (c) 2004 Andy Jefferson and others. All rights reserved.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.//from w w w  .j a v a  2s. c om

 Contributions
 ...
 ***********************************************************************/

import java.util.HashSet;
import java.util.Iterator;

import java.util.Collection;

public class Main {
    /**
     * Compares two sets of Objects.  Returns true if and only if the two
     * sets contain the same number of objects and each element of the first
     * set has a corresponding element in the second set whose fields compare
     * equal according to the compareTo() method.
     *
     * @return  <tt>true</tt> if the sets compare equal,
     *          <tt>false</tt> otherwise.
     */

    public static boolean compareSet(Collection s1, Collection s2) {
        if (s1 == null) {
            return s2 == null;
        } else if (s2 == null) {
            return false;
        }

        if (s1.size() != s2.size()) {
            return false;
        }

        HashSet set2 = new HashSet(s2);

        Iterator i = s1.iterator();

        while (i.hasNext()) {
            Object obj = i.next();

            boolean found = false;
            Iterator j = set2.iterator();

            while (j.hasNext()) {
                if (obj.equals(j.next())) {
                    j.remove();
                    found = true;
                    break;
                }
            }

            if (!found)
                return false;
        }

        return true;
    }
}

Related

  1. compareCollections(Collection a, Collection b)
  2. compareCollections(Collection cola, Collection colb)
  3. compareCollections(Collection value1, Collection value2)
  4. compareExactOrder(Collection c1, Collection c2)
  5. compareRef(final Collection left, final Collection right)
  6. compareTo(Collection o1, Collection o2)
  7. compareTo(Collection a, Collection b)