Java Collection Equal isCollectionsEqual(Collection f1, Collection f2)

Here you can find the source of isCollectionsEqual(Collection f1, Collection f2)

Description

Compare two collections.

License

Apache License

Parameter

Parameter Description
f1 Collection
f2 Collection

Return

true if collections have the same size and each element is present in the other

Declaration

public static boolean isCollectionsEqual(Collection f1, Collection f2) 

Method Source Code

//package com.java2s;
/**/*www  .j ava  2  s . c  o  m*/
 * Copyright 2012 Comcast Corporation
 * 
 * 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.
 */

import java.util.Collection;

public class Main {
    /**
     * Compare two collections. Method should be called form equals() method impls
     * Note: The order of collections does not matter
     * @param f1 Collection
     * @param f2 Collection
     * @return true if collections have the same size and each element is present in the other
     */
    public static boolean isCollectionsEqual(Collection f1, Collection f2) {
        if ((f1 == null && f2 != null) || (f1 != null && f2 == null)) {
            return false;
        }
        if (f1 != null) {
            if ((f1.size() != f2.size()) || !isC2InC1(f1, f2) || !isC2InC1(f2, f1)) {
                return false;
            }
        }
        return true;
    }

    /**
     * return true if all elements of c2 are in c1
     * @param <T>
     * @param c1
     * @param c2
     * @return
     */
    public static <T> boolean isC2InC1(Collection<T> c1, Collection<T> c2) {
        for (T e1 : c1) {
            boolean e1found = false;
            for (T theirPlayer : c2) {
                if (e1.equals(theirPlayer)) {
                    e1found = true;
                    break;
                }
            }
            if (!e1found) {
                return false;
            }
        }
        return true;
    }
}

Related

  1. equalsUnorderedCollections(Collection a, Collection b)
  2. equalTestData(Collection receivedDataSet)
  3. getContainedEquals(Collection a, T b)
  4. indexOfEquals(Collection collection, T element)
  5. isCollectionEqual(Collection c1, Collection c2)
  6. isContentEqual(final Collection collectionA, final Collection collectionB)
  7. isEqual(Collection left, Collection right)
  8. isEqual(Collection one, Collection two)
  9. isEqual(Collection coll, Comparator comp)