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