Java Collection Contain containsAny(Collection col1, Collection col2)

Here you can find the source of containsAny(Collection col1, Collection col2)

Description

Tests if any value in one collection is part of another collection

License

Apache License

Parameter

Parameter Description
col1 First collection
col2 Second collection

Return

The first matching object, if any matches. If there are not matches returns null.<

Declaration

public static Object containsAny(Collection<?> col1, Collection<?> col2) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2009, 2010 Innovation Gate GmbH
 * //from  www. j  av a2  s . c  o  m
 * 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;

import java.util.Iterator;

public class Main {
    /**
     * Tests if any value in one collection is part of another collection
     * 
     * @param col1
     *            First collection
     * @param col2
     *            Second collection
     * @return The first matching object, if any matches. If there are not
     *         matches returns null.<
     */
    public static Object containsAny(Collection<?> col1, Collection<?> col2) {

        Collection<?> largerCol;
        Collection<?> smallerCol;

        if (col1.size() > col2.size()) {
            largerCol = col1;
            smallerCol = col2;
        } else {
            largerCol = col2;
            smallerCol = col1;
        }

        Iterator<?> smallerValues = smallerCol.iterator();
        Object value;
        while (smallerValues.hasNext()) {
            value = smallerValues.next();
            if (largerCol.contains(value)) {
                return value;
            }
        }

        return null;

    }
}

Related

  1. containSameElements(Collection> sets)
  2. containSameItems(Collection c1, Collection c2)
  3. containsAny(Collection c1, Collection c2)
  4. containsAny(Collection collection1, Collection collection2)
  5. containsAny(Collection container, Collection contained)
  6. containsAny(Collection source, Collection candidates)
  7. containsAny(Collection source, Object... candidates)
  8. containsAny(Collection collection1, Collection collection2)
  9. containsAny(Collection c1, Collection c2)