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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Im unable to create allBs as type B, it only works if I make the list of type A. The error I get is: Required List B, but 'collect' was inferred to R
@Hdot Sorry fixed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.