Java 8 Lambda Stream forEach with multiple statements

前端 未结 4 922
心在旅途
心在旅途 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:25

    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.

提交回复
热议问题