Java 8 Lambda Stream forEach with multiple statements

前端 未结 4 880
心在旅途
心在旅途 2021-02-01 12:44

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 L         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-01 13:23

    In the first case alternatively to multiline forEach you can use the peek stream operation:

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

    In the second case I'd suggest to extract the loop body to the separate method and use method reference to call it via forEach. Even without lambdas it would make your code more clear as the loop body is independent algorithm which processes the single entry so it might be useful in other places as well and can be tested separately.

    Update after question editing. if you have checked exceptions then you have two options: either change them to unchecked ones or don't use lambdas/streams at this piece of code at all.

提交回复
热议问题