我想知道是否可以在不调用函数的情况下更改属性的值,例如:
return findAll().stream()
.map(cps -> cps.setFavorited(true))
.distinct()
.collect(toList());
答案 0 :(得分:2)
如果我对您的理解正确,那么您的流解决方案将类似于:
return findAll().stream()
.map(cps -> {cps.setFavorited(true); return cps;})
.distinct()
.collect(toList());
或者您的setFavorited
可以返回this
,从而允许链接:
public <Whatever> setFavorited(boolean flag){
this.favorited = flag;
return this;
}
但是您在这些事情上必须非常小心,因为您所关心的只是distinct
(至少依赖于 equals
)。流实现可能检测到您的equals
可能基于favorited
之外的其他属性,因此,从理论上讲,它可能会完全跳过该map
。这可能是牵强附会的,但是在java-9
中,这是一种优化:
Stream.of(1,2,3)
.map(x -> x + 1)
.count();
由于您只关心count
,因此map
被跳过。