Java stream “forEach” but not consuming stream

时光毁灭记忆、已成空白 提交于 2019-12-18 22:33:41

问题


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 example could look like this, unfortunately this does not work as forEach consumes the 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?


回答1:


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());


来源:https://stackoverflow.com/questions/35364792/java-stream-foreach-but-not-consuming-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!