How to read only certain type objects from a collection with several types of objects

I have a collection with two types of objects. I only want to read one of two types in a new set. Is there an elegant way to do this?

+6
source share
2 answers

Use the Google Guava filter.

Collections2.filter(yourOriginalCollection, new Predicate<Object>() { public boolean apply(Object obj) { return obj instanceof TypeYouAreInterestedIn; } }); 

Or in Java 8:

 Collections2.filter(yourOriginalCollection, (obj) -> obj instanceof TypeYouAreInterestedIn); 
+5
source

Like Suresh said that there are no built-in functions, here is some complete code:

 for(Object obj : yourOldCollection) { if(obj instanceof SearchedType){ yourNewSet.add(obj); } } 
+1
source

All Articles