Search code examples
javalambdajava-8

Java 8 Lambda Stream forEach with multiple statements


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

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?


Solution

  • WARNING
    As mentioned in comments, Using peek() for production code is considered bad practice
    The reasson is that "According to its JavaDocs, the intermediate Stream operation java.util.Stream.peek() “exists mainly to support debugging” purposes."
    As a consequence, this proposed solution SHOULD NOT be used.


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

    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.