Hdot
Hdot

Reputation: 583

Instantiate ArrayList with map from another ArrayList

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?

Upvotes: 1

Views: 178

Answers (1)

GBlodgett
GBlodgett

Reputation: 12819

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

Upvotes: 3

Related Questions