Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a list during a stream operation

Here's my scenario:

private List<Entity> getPlanets() {
   return entities.values()
                  .stream()
                  .filter(x -> x instanceof Planet)
                  .collect(Collectors.toList());
}
  • Entity is the super class of Planet
  • entities is a HashMap<Entity>
  • As the method is called "getPlanets" I would like it to return a List<Planet> but it appears to me that the stream expression is going to return a List<Entity>
  • I tried some casting expressions but none seem to work out.

I am brand new with Java 8 streams so maybe someone can point out what I am missing?

like image 497
pitosalas Avatar asked Mar 18 '16 21:03

pitosalas


1 Answers

return entities.values()
               .stream()
               .filter(x -> x instanceof Planet)
               .map(x -> (Planet) x)
               .collect(Collectors.toList());
like image 74
Louis Wasserman Avatar answered Oct 15 '22 05:10

Louis Wasserman