具有多个语句的Java 8 Lambda Stream forEach [英] Java 8 Lambda Stream forEach with multiple statements

查看:2613
本文介绍了具有多个语句的Java 8 Lambda Stream forEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am still in the process of learning Lambda, please excuse me If I am doing something wrong

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 可以执行一个声明而已。它不会返回更新的流或函数以进一步处理。我可能完全选择了错误的一个。

Seems like forEach can be executed for one statement only. It doesn't return updated stream or function to process further. I might have selected wrong one altogether.

有人可以指导我如何有效地做到这一点吗?

Can someone guide me how to do this effectively?

还有一个问题,

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表达式?

How do I convert this to Lambda expression?

推荐答案

忘记与第一个代码段相关联。我根本不会使用 forEach 。由于您要将 Stream 的元素收集到 List 中,因此结束<$ c更有意义$ c> Stream 使用 collect 进行处理。然后你需要 peek 来设置ID。

Forgot to relate to the first code snippet. I wouldn't use forEach at all. Since you are collecting the elements of the Stream into a List, it would make more sense to end the Stream processing with collect. Then you would need peek in order to set the ID.

List<Entry> updatedEntries = 
    entryList.stream()
             .peek(e -> e.setTempId(tempId))
             .collect (Collectors.toList());

对于第二个片段, forEach 可以执行多个表达式,就像任何lambda表达式一样:

For the second snippet, forEach can execute multiple expressions, just like any lambda expression can :

entryList.forEach(entry -> {
  if(entry.getA() == null){
    printA();
  }
  if(entry.getB() == null){
    printB();
  }
  if(entry.getC() == null){
    printC();
  }
});

但是(查看您的评论尝试),您无法在此方案中使用过滤器,因为您只会处理一些条目(例如, entry.getA()== null 的条目)。

However (looking at your commented attempt), you can't use filter in this scenario, since you will only process some of the entries (for example, the entries for which entry.getA() == null) if you do.

这篇关于具有多个语句的Java 8 Lambda Stream forEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆