java stream lambda,具有多个语句的Java 8 Lambda Stream forEach

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

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));

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?

One more question,

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?

How do I convert this to Lambda expression?

解决方案

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 updatedEntries =

entryList.stream()

.peek(e -> e.setTempId(tempId))

.collect (Collectors.toList());

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();

}

});

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值