问题
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.
回答1:
You need to cast the objects:
List<SomeChildType> myChildList = myList.stream()
.filter(SomeChildType.class::isInstance)
.map(SomeChildType.class::cast)
.collect(toList())
来源:https://stackoverflow.com/questions/34879086/java-8-stream-api-filter-on-instance-and-cast