我还在学习Lambda,如果做错了请见谅
final Long tempId = 12345L;
List<Entry> updatedEntries = new LinkedList<>();
for (Entry entry : entryList) {
entry.setTempId(tempId);
updatedEntries.add(entityManager.update(entry, entry.getId()));
}
//entryList.stream().forEach(entry -> entry.setTempId(tempId));
似乎 forEach
只能为一个语句执行。它不会返回更新的流或函数以进一步处理。我可能完全选错了。
有人可以指导我如何有效地做到这一点吗?
还有一个问题,
public void doSomething() throws Exception {
for(Entry entry: entryList){
if(entry.getA() == null){
printA() throws Exception;
}
if(entry.getB() == null){
printB() throws Exception;
}
if(entry.getC() == null){
printC() throws Exception;
}
}
}
//entryList.stream().filter(entry -> entry.getA() == null).forEach(entry -> printA()); something like this?
如何将其转换为 Lambda 表达式?
最佳答案
忘记与第一个代码片段相关。我根本不会使用 forEach
。由于您将 Stream
的元素收集到 List
中,因此使用 collect< 结束
。然后你需要 Stream
处理会更有意义peek
来设置 ID。
List<Entry> updatedEntries =
entryList.stream()
.peek(e -> e.setTempId(tempId))
.collect (Collectors.toList());
对于第二个片段,forEach
可以执行多个表达式,就像任何 lambda 表达式一样:
entryList.forEach(entry -> {
if(entry.getA() == null){
printA();
}
if(entry.getB() == null){
printB();
}
if(entry.getC() == null){
printC();
}
});
但是(查看您的评论尝试),您不能在这种情况下使用过滤器,因为您只会处理一些条目(例如, entry.getA() == null 的条目
)如果你这样做。
关于具有多个语句的 Java 8 Lambda Stream forEach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31130457/