Returns all occurrences objects satisfying some criterion in the given collection. - Java java.util

Java examples for java.util:Collection Search

Description

Returns all occurrences objects satisfying some criterion in the given collection.

Demo Code

/*******************************************************************************
 * Copyright (c) 2010 SAP AG.//from   ww w.  ja va2  s. c  o m
 * 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:
 *    Emil Simeonov - initial API and implementation.
 *    Dimitar Donchev - initial API and implementation.
 *    Dimitar Tenev - initial API and implementation.
 *    Nevena Manova - initial API and implementation.
 *    Georgi Konstantinov - initial API and implementation.
 *    Jakob Spies - initial API and implementation.
 *******************************************************************************/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class Main{
    /**
     * Returns all occurrences objects satisfying some <code>criterion</code> in the given collection.
     * @param objects the set to search
     * @param criterion the search criterion
     * @param <T> the object type
     * @return the objects satisfying the <code>criterion</code>
     * @pre objects != null
     * @pre criterion != null
     * @post return != null
     */
    public static <T> Set<T> findAllAsSet(final Collection<T> objects,
            final Condition<? super T> criterion) {
        Nil.checkNil(objects, "objects"); //$NON-NLS-1$
        Nil.checkNil(criterion, "criterion"); //$NON-NLS-1$

        Set<T> found = null;

        for (final T obj : objects) {
            if (criterion.isSatisfied(obj)) {
                if (found == null) {
                    found = new HashSet<T>();
                }
                found.add(obj);
            }
        }

        if (found == null) {
            found = Collections.emptySet();
        }

        return found;
    }
}

Related Tutorials