Skip to content
Advertisement

Non-terminal forEach() in a stream?

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 suspect I could do this with something like .map(item -> f(item)) where the method f performs the side effect and returns the item to the stream, but it seems a tad hokey.

Is there a standard way of handling this?

Advertisement

Answer

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());
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement