Java stream “forEach” but not consuming stream

后端 未结 1 1546
一向
一向 2021-01-05 03:37

Sometimes it would be handy do \"something\" (e.g. print) with every element in a stream in between steps of processing the stream, e.g. for debugging.

A simple exa

相关标签:
1条回答
  • 2021-01-05 04:01

    You are looking for the peek operation:

    This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline

    This method will execute the given action on all elements of the Stream pipeline as they are consumed. As such, it allows to take a peek of the elements.

    List<String> filteredList = 
        list.stream()
            .filter(s -> s.startsWith("t"))
            .peek(System.out::println)
            .collect(Collectors.toList());
    
    0 讨论(0)
提交回复
热议问题