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; } 
importfor the same class? what is the type ofnode.bodyDeclarations? (and do not share images for code)node?).public List bodyDeclarations()returns a raw type.((List<?>)node.bodyDeclarations()).stream()as the starting point of the stream operation. The cast will not issue any warning as you are denoting that the list element type is unknown, but the subsequent operations are not using raw types anymore, so the.map(AnnotationTypeMemberDeclaration.class::cast)will have the desired effect.