dje*_*lin 5 java java-8 java-stream
请不要"如果"声明,除非你解释为什么没有一个是不可能的.
我看到我只能在流上运行多远.我有这种麻烦:
List<Cube> revised =
cubes.filter(p)
.map(c -> f(c))
.map(c -> {
if(c.prop()) {
c.addComment(comment);
}
return c;
})
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
如果没有"if",如何做到这一点我最好的想法是
List<Cube> revised =
cubes.filter(p)
.map(c -> f(c));
revised
.filter(Cube::prop)
.forEach(c -> c.addComment(comment)); // can also map still
Run Code Online (Sandbox Code Playgroud)
有没有办法只在一个链中做到这一点?如果是这样,分支基本上必须在流中发生.一种类似的方法forSome(predicate, lambda)
.
不想"滚动我自己的"任何东西.我可以使用"if",但我正在尝试学习具有表现力的功能风格.
当您有 时,无需使用map
返回相同元素的方法peek
。以下代码通过使用短路运算符进行“欺骗”:
cubes.filter(p)
.map(c -> f(c))
.peek(c -> c.prop() && c.addComment(comment))
Run Code Online (Sandbox Code Playgroud)
我认为使用Optional的“现代”方式的可读性要差得多:
cubes.filter(p)
.map(c -> f(c))
.peek(c -> Optional.of(c).filter(Cube::prop).ifPresent(c -> c.addComment(comment)))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
153 次 |
最近记录: |