Java 8 Stream API:过滤实例并进行转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34879086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:29:37  来源:igfitidea点击:

Java 8 Stream API : Filter on instance, and cast

javajava-8

提问by Thibaut D.

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.

我不知道如何收集以获得正确的列表类型。

回答by assylias

You need to cast the objects:

您需要投射对象:

List<SomeChildType> myChildList = myList.stream()
                                        .filter(SomeChildType.class::isInstance)
                                        .map(SomeChildType.class::cast)
                                        .collect(toList())