Checks if the given two Collection s contains the same elements in any order. - Java java.util

Java examples for java.util:Collection Contain

Description

Checks if the given two Collection s contains the same elements in any order.

Demo Code

/*******************************************************************************
 * Copyright (c) 2014 Karlsruhe Institute of Technology, Germany
 *                    Technical University Darmstadt, Germany
 *                    Chalmers University of Technology, Sweden
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*w  ww  .ja v a 2  s . c  om*/
 *    Technical University Darmstadt - initial API and implementation and/or initial documentation
 *******************************************************************************/
//package com.java2s;

import java.util.Collection;
import java.util.Iterator;

import java.util.LinkedList;

public class Main {
    public static void main(String[] argv) {
        Collection first = java.util.Arrays.asList("asdf", "java2s.com");
        Collection second = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(containsSame(first, second));
    }

    /**
     * <p>
     * Checks if the given two {@link Collection}s contains the same elements
     * in any order.
     * </p>
     * <p>
     * Empty {@link Collection}s and {@code null} parameters are treated as equal.
     * </p> 
     * @param first The first {@link Collection}.
     * @param second The second {@link Collection}.
     * @return {@code true} both {@link Collection}s contains same elements, {@code false} {@link Collection}s are different.
     */
    public static <T> boolean containsSame(Collection<T> first,
            Collection<T> second) {
        if (first != null) {
            if (second != null) {
                if (first.size() == second.size()) {
                    Collection<T> firstCopy = new LinkedList<T>(first);
                    boolean same = true;
                    Iterator<T> secondIter = second.iterator();
                    while (same && secondIter.hasNext()) {
                        T secondNext = secondIter.next();
                        same = firstCopy.remove(secondNext);
                    }
                    return same;
                } else {
                    return false;
                }
            } else {
                return first.size() == 0;
            }
        } else {
            return second == null || second.size() == 0;
        }
    }
}

Related Tutorials