Returns all occurrences of objects of a certain runtime type in the given collection. - Java java.util

Java examples for java.util:Collection Search

Description

Returns all occurrences of objects of a certain runtime type in the given collection.

Demo Code

/*******************************************************************************
 * Copyright (c) 2010 SAP AG./*from  www . j  a v a2s .  co  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{
    public static void main(String[] argv){
        Collection objects = java.util.Arrays.asList("asdf","java2s.com");
        Class type = String.class;
        System.out.println(findAllOfType(objects,type));
    }
    /**
     * Returns all occurrences of objects of a certain runtime type
     * in the given collection.
     * @param objects the set to search
     * @param type the target type
     * @param <T> the target type
     * @return the objects of type <code>type</code> 
     * @pre objects != null
     * @pre type != null
     * @post return != null
     */
    public static <T> Collection<T> findAllOfType(
            final Collection<? super T> objects, final Class<T> type) {
        Nil.checkNil(objects, "objects"); //$NON-NLS-1$
        Nil.checkNil(type, "type"); //$NON-NLS-1$

        Collection<T> found = null;

        for (final Object obj : objects) {
            if (type.isInstance(obj)) {
                if (found == null) {
                    found = new LinkedList<T>();
                }
                found.add((T) obj);
            }
        }

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

        return found;
    }
}

Related Tutorials