2

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?

enter image description here

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; } 
7
  • do you by any chance have differrent package import for the same class? what is the type of node.bodyDeclarations? (and do not share images for code) Commented Apr 27, 2020 at 7:52
  • 1
    Can you post the code as code so it's possible to copy paste it? And can you give a complete example (for example: what is the type of node?). Commented Apr 27, 2020 at 8:05
  • 2
    The problem is that public List bodyDeclarations() returns a raw type. Commented Apr 27, 2020 at 14:46
  • 2
    Will it help if bodyDeclarations() starts returning List< AnnotationTypeMemberDeclaration>, not the rawtype as was correctly mentioned? Commented Apr 27, 2020 at 15:18
  • 3
    Then use ((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. Commented Apr 28, 2020 at 9:29

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.