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

帅比萌擦擦* 提交于 2020-06-24 08:12:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!