Java: selecting from a collection only elements of the provided type

I have a set of elements of type B and C that all extend A. I need to filter the collection to get only elements of type B.

Is there any way to do this other than:

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

thanks

+4
source share
5 answers

Guava was mentioned in other answers, but not a specific solution, which is even simpler than people understand:

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

It is simple and clean, does the right thing, creates only one instance and does not copy anything and does not cause any warnings.

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

+11
source

I do not see anything wrong with this, as in your example. However, if you want a fantasy, you can use the Google Guava library , in particular the Collections2 class, to filter the functional style on your collection. You can provide your own predicate, which can of course do an instanceof thing.

 Collection<Object> newCollection = Collections2.filter(initCollection, new Predicate<Object>() { public boolean apply(Object o) { return !(o instanceof String); } }); 
+4
source

AFAIK, there is no easy way to do this without adding code to classes A, B, and C. The real question is: why do you need to filter out elements of a certain type? This contradicts the very idea of ​​imprinting in OOP.

+2
source

If you do not want to create a new collection, you can remove the odd items from the existing one:

 Iterator<A> it = initCollection.iterator(); while (it.hasNext()){ if (it.next() instanceof C) { it.remove(); } } 
0
source

This is an old question, but I thought I would add it if anyone finds it.

You can do this using pure Java 8 and its Stream s.

 List<B> filtered = listOfA.stream() .filter(a -> a instanceof B) .map(a -> (B) a) .collect(Collectors.toList()); 
0
source

Source: https://habr.com/ru/post/1308145/


All Articles