简体   繁体   English

在流操作期间转换列表

[英]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 EntityPlanet的超级类
  • entities is a HashMap<Entity> 实体是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> 由于该方法被称为“getPlanets”,我希望它返回List<Planet>但在我看来,流表达式将返回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? 我是全新的Java 8流,所以也许有人可以指出我缺少的东西?

return entities.values()
               .stream()
               .filter(x -> x instanceof Planet)
               .map(x -> (Planet) x)
               .collect(Collectors.toList());

A variation with method references: 方法参考的变体:

return entities.values().stream()
    .filter(Planet.class::isInstance)
    .map(Planet.class::cast)
    .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM