Need to cast the list again after already filtering and casting objects with Java 8 Stream API

倖福魔咒の 提交于 2020-05-13 13:57:21

问题


I have a list of objects, and I want to filter out those objects of a specific type, cast and collect them into a new list. That's why I use the stream API suggested in the following questions:

Java 8 Stream API : Filter on instance, and cast

Is it possible to cast a Stream in Java 8?

However, Intellij tells me that I have to cast the collected list again after filtering&casting&collecting, I want to figure out why? And, if I accept the suggestion, the error goes away, but is that the right way to do it?

Background: I am developing a static program analysis with Eclipse JDT, so I am overwriting the visit() methods to process AST nodes with specific type.

Here is my code processing the AnnotationTypeDeclaration:

  @Override
  public boolean visit(AnnotationTypeDeclaration node) {
    List<AnnotationTypeMemberDeclaration> memberDeclarations = (List<AnnotationTypeMemberDeclaration>) node.bodyDeclarations().stream()
            .filter(AnnotationTypeMemberDeclaration.class::isInstance)
            .map(AnnotationTypeMemberDeclaration.class::cast)
            .collect(Collectors.toList());
    // ... do something with the memberDeclarations
    return true;
}

Here is the definition of annotationTypeDeclaration.bodyDeclarations():

    public List bodyDeclarations() {
        return this.bodyDeclarations;
    }

来源:https://stackoverflow.com/questions/61453941/need-to-cast-the-list-again-after-already-filtering-and-casting-objects-with-jav

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