Gets the instances of Class c in iterable - Java Collection Framework

Java examples for Collection Framework:Iterable

Description

Gets the instances of Class c in iterable

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;

public class Main {
    /**/*from   w w  w  .  jav  a 2 s .co  m*/
     * Gets the instances of Class c in iterable
     * @param iterable iterable with instances
     * @param c class of generic type E
     * @param <E> Type of the list to return and the generic of c
     * @return List\<E> where object in list is an instanceof class c of generic type E
     */
    public static <E> List<E> getInstances(Iterable iterable, Class<E> c) {
        ArrayList<E> result = new ArrayList<E>();
        for (Object obj : iterable) {
            if (c.isInstance(obj)) {
                result.add(c.cast(obj));
            }
        }
        return result;
    }
}

Related Tutorials