[英]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
Entity
是Planet
的超级类 HashMap<Entity>
实体是HashMap<Entity>
List<Planet>
but it appears to me that the stream expression is going to return a List<Entity>
由于该方法被称为“getPlanets”,我希望它返回List<Planet>
但在我看来,流表达式将返回List<Entity>
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.