Filters the src collection and puts the objects matching the clazz into the dest collection. - Java java.util

Java examples for java.util:Collection Filter

Description

Filters the src collection and puts the objects matching the clazz into the dest collection.

Demo Code


//package com.book2s;
import java.util.*;

public class Main {
    public static void main(String[] argv) {
        Class clazz = String.class;
        Collection src = java.util.Arrays.asList("asdf", "book2s.com");
        System.out.println(filter(clazz, src));
    }//from w ww. ja v  a2  s.c  o  m

    /**
     * Filters the src collection and puts the objects matching the
     * clazz into the dest collection.
     */
    public static <T> void filter(Class<T> clazz, Collection<?> src,
            Collection<T> dest) {
        for (Object o : src) {
            if (clazz.isInstance(o)) {
                dest.add(clazz.cast(o));
            }
        }
    }

    /**
     * Filters the src collection and puts all matching objects into
     * an ArrayList, which is then returned.
     */
    public static <T> Collection<T> filter(Class<T> clazz, Collection<?> src) {
        Collection<T> result = new ArrayList<T>();
        filter(clazz, src, result);
        return result;
    }
}

Related Tutorials