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
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>
.)
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With