Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream API : Filter on instance, and cast [duplicate]

Tags:

java

java-8

I have a list of objects:

List<SomeType> myList;

I want to get a list of sub-types available in this list:

List<SomeChildType> myChildList = myList.stream().filter(e -> e instanceof SomeChildType).collect(??????)

I don't know how to collect to obtain the correct list type.

like image 293
Thibaut D. Avatar asked Jan 19 '16 14:01

Thibaut D.


1 Answers

You need to cast the objects:

List<SomeChildType> myChildList = myList.stream()
                                        .filter(SomeChildType.class::isInstance)
                                        .map(SomeChildType.class::cast)
                                        .collect(toList())
like image 156
assylias Avatar answered Oct 21 '22 20:10

assylias