具有多个语句的Java 8 Lambda Stream forEach

我还在学习Lambda,请原谅我如果我做错了什么

final Long tempId = 12345L; List 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 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(); } }); 

但是(查看您的注释尝试),您不能在此方案中使用filter,因为您只会处理某些条目(例如, entry.getA() == null的条目)。

在第一种情况下,替换为multiline forEach您可以使用peek stream操作:

 entryList.stream() .peek(entry -> entry.setTempId(tempId)) .forEach(updatedEntries.add(entityManager.update(entry, entry.getId()))); 

在第二种情况下,我建议将循环体提取到单独的方法,并使用方法引用通过forEach调用它。 即使没有lambdas,它也会使你的代码更加清晰,因为循环体是处理单个条目的独立算法,所以它在其他地方也可能有用,并且可以单独测试。

问题编辑后更新 。 如果您已经检查了exception,那么您有两个选择:将它们更改为未选中的或者根本不在这段代码中使用lambdas / streams。

 List items = new ArrayList<>(); items.add("A"); items.add("B"); items.add("C"); items.add("D"); items.add("E"); //lambda //Output : A,B,C,D,E items.forEach(item->System.out.println(item)); //Output : C items.forEach(item->{ System.out.println(item); System.out.println(item.toLowerCase()); } }); 

您不必将多个操作塞入一个流/ lambda。 考虑将它们分成2个语句(使用toList()静态导入):

 entryList.forEach(e->e.setTempId(tempId)); List updatedEntries = entryList.stream() .map(e->entityManager.update(entry, entry.getId())) .collect(toList());