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>
.)