Non-terminal forEach() in a stream?

前端 未结 2 1754
时光取名叫无心
时光取名叫无心 2021-02-18 14:35

Sometimes when processing a Java stream() I find myself in need of a non-terminal forEach() to be used to trigger a side effect but without terminating processing.

I sus

2条回答
  •  無奈伤痛
    2021-02-18 15:03

    Yes there is. It is called peek() (example from the JavaDoc):

    Stream.of("one", "two", "three", "four")
         .peek(e -> System.out.println("Original value: " + e))
         .filter(e -> e.length() > 3)
         .peek(e -> System.out.println("Filtered value: " + e))
         .map(String::toUpperCase)
         .peek(e -> System.out.println("Mapped value: " + e))
         .collect(Collectors.toList());
    

提交回复
热议问题