Java 8 Lambda Stream forEach with multiple statements

前端 未结 4 881
心在旅途
心在旅途 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.

    0 讨论(0)
  • 2021-02-01 13:24
    List<String> items = new ArrayList<>();
    items.add("A");
    items.add("B");
    items.add("C");
    items.add("D");
    items.add("E");
    
    //lambda
    //Output : A,B,C,D,E
    items.forEach(item->System.out.println(item));
    
    //Output : C
    items.forEach(item->{
        System.out.println(item);
        System.out.println(item.toLowerCase());
      }
    });
    
    0 讨论(0)
  • 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<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.

    0 讨论(0)
  • 2021-02-01 13:31

    You don't have to cram multiple operations into one stream/lambda. Consider separating them into 2 statements (using static import of toList()):

    entryList.forEach(e->e.setTempId(tempId));
    
    List<Entry> updatedEntries = entryList.stream()
      .map(e->entityManager.update(entry, entry.getId()))
      .collect(toList());
    
    0 讨论(0)
提交回复
热议问题