问题
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