Java examples for java.util:Collection Contain
Cast objects matching class, ignore rest; no ClassCastException will occur Use when objects may contain classes that are not desired
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class Main{ public static void main(String[] argv){ Class clazz = String.class; Collection objects = java.util.Arrays.asList("asdf","java2s.com"); System.out.println(castMatching(clazz,objects)); }/*from ww w . j av a 2 s .com*/ /** * Cast objects matching class, ignore rest; no ClassCastException will occur<br> * <br> * Use when objects may contain classes that are not desired */ public static <A extends Object> List<A> castMatching(Class<A> clazz, Collection<? extends Object> objects) { return cast(clazz, objects, CastOption.MATCHING); } /** * Cast objects to clazz * * @param castOption if ALL, cast all and throw exception if cast fails; if MATCHING, only cast those of type clazz */ @SuppressWarnings("unchecked") private static <A extends Object> List<A> cast(Class<A> clazz, Collection<? extends Object> objects, CastOption castOption) { List<A> results = new ArrayList<A>(objects.size()); for (Object object : objects) { if ((castOption == CastOption.ALL) || ((castOption == CastOption.MATCHING) && (object .getClass().isAssignableFrom(clazz)))) { results.add((A) object); } } return results; } }