Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read only specific objects of a type from a collection with multiple object types

I have a collection with two object types. I want to only read one of the two types into a new Set. Is there an elegant way of doing this?

like image 890
Scy Avatar asked Oct 21 '15 11:10

Scy


1 Answers

Use Google Guava's 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);
like image 122
Steve Kuo Avatar answered Oct 30 '22 17:10

Steve Kuo