Java stream "forEach" but does not consume a stream

Sometimes it would be convenient to do something (for example, printing) with each flow element between the stages of flow processing, for example. for debugging.

A simple example might look like this, unfortunately this does not work, since forEach consumes a stream:

 List<String> list = new ArrayList<>(); list.add("one"); list.add("two"); list.add("three"); list.add("four"); List<String> filteredList = list.stream() .filter(s -> s.startsWith("t")) .forEach(System.out::println) .collect(Collectors.toList()); 

How can this be achieved?

+6
source share
1 answer

You are looking for peek operation:

This method exists mainly to support debugging when you want to see elements while passing a certain point in the pipeline

This method will perform this action for all elements of the Stream pipeline when they are consumed. Thus, it allows you to take peek items.

 List<String> filteredList = list.stream() .filter(s -> s.startsWith("t")) .peek(System.out::println) .collect(Collectors.toList()); 
+12
source

All Articles