Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: select from collection only elements of provided type

I have a collection of elements of type B and C, which all extends A. I need to filter the collection to get elements of only B type.

Is there any way to do it except:

for (A a : initCollection) {
  if (a instanceof B) {
    newCollection.add(a)?
  }
}

Thanks

like image 884
glaz666 Avatar asked Dec 04 '22 12:12

glaz666


2 Answers

Guava was alluded to in other answers, but not the specific solution, which is even simpler than people realize:

Iterable<B> onlyBs = Iterables.filter(initCollection, B.class);

It's simple and clean, does the right thing, only creates a single instance and copies nothing, and doesn't cause any warnings.

(The Collections2.filter() method does not have this particular overload, though, so if you really want a Collection, you'll have to provide Predicates.instanceOf(B.class) and the resulting collection will still sadly be of type Collection<A>.)

like image 173
Kevin Bourrillion Avatar answered Feb 23 '23 05:02

Kevin Bourrillion


I don't see anything wrong with doing it as per your example. However, if you want to get fancy you could use Google's Guava library, specifically the Collections2 class, to do a functional-style filtering on your collection. You get to provide your own predicate, which can of course do the instanceof thing.

Collection<Object> newCollection = Collections2.filter(initCollection, new Predicate<Object>() { 
    public boolean apply(Object o) {
        return !(o instanceof String);
    } 
});
like image 28
Carl Smotricz Avatar answered Feb 23 '23 07:02

Carl Smotricz