1

I have a current ArrayList of type A and I want to create a new list of all the object in this list that is of type B where B is a sub-class of A. Is there a way to do this using a map()?

ArrayList<B> allBs = allAs.stream().map( b -> where b instanceof B)

That would maybe look something like this?

Hdot
  • 543
  • 1
  • 4
  • 15

1 Answers1

3

You can do this with the filter function:

List<B> allBs = allAs.stream()
                     .filter(B.class::isInstance)  
                     .map(B.class::cast)
                     .collect(Collectors.toList());

Which will filter out any elements that don't match the given predicate, cast them to B objects, and then collect it to a new List.

Also note that I changed ArrayList<B> allBs to List<B> allBs, because it is good practice to program to the interface

GBlodgett
  • 12,704
  • 4
  • 31
  • 45