Returns a filtered copy of the collection - Java java.util

Java examples for java.util:Collection Filter

Description

Returns a filtered copy of the collection

Demo Code


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

public class Main {
    public static void main(String[] argv) {
        Collection coll = java.util.Arrays.asList("asdf", "book2s.com");
        System.out.println(cloneCollection(coll));
    }/*from   ww w .j  ava 2s  . c  om*/

    /**
     * Returns a filtered copy of the collection <code>coll</code>.
     *
     * @param coll the collection to filter.
     * @param p the predicate to filter by.
     * @return a new collection.
     */

    /*public static <T> Collection<T> filter(Collection<T> coll, Predicate<T> p){
        Collection<T> c2 = newCollection(coll);
        for(T obj: coll)
            if(p.apply(obj))
                c2.add(obj);
        return c2;
    }*/

    private static <T> Collection<T> cloneCollection(Collection<T> coll) {
        try {
            Class cl = coll.getClass();
            Constructor con = cl
                    .getConstructor(new Class[] { Collection.class });
            return (Collection<T>) con.newInstance(new Object[] { coll });
        } catch (Exception e) {
            if (coll instanceof List)
                return new LinkedList<T>(coll);
            if (coll instanceof Set)
                return new HashSet<T>(coll);
            throw new RuntimeException("Cannot handle this collection");
        }
    }
}

Related Tutorials