In java, why stream peek is not working for me?

落爺英雄遲暮 提交于 2021-02-04 19:09:18

问题


we have peek function on stream which is intermediate function which accepts consumer. Then in my case why doesn't it replace "r" with "x". peek should ideally used for debugging purpose but I was just wondering why didn't it worked here.

List<String> genre = new ArrayList<String>(Arrays.asList("rock", "pop", "jazz", "reggae")); 
System.out.println(genre.stream().peek(s-> s.replace("r","x")).peek(s->System.out.println(s)).filter(s -> s.indexOf("x") == 0).count()); 

回答1:


Because peek() accepts a Consumer.
A Consumer is designed to accept argument but returns no result.

For example here :

genre.stream().peek(s-> s.replace("r","x"))

s.replace("r","x") is indeed performed but it doesn't change the content of the stream.
It is just a method-scoped String instance that is out of the scope after the invocation of peek().

To make your test, replace peek() by map() :

List<String> genre = new ArrayList<String>(Arrays.asList("rock", "pop", "jazz", "reggae"));
System.out.println(genre.stream().map(s -> s.replace("r", "x"))
                                 .peek(s -> System.out.println(s))
                                 .filter(s -> s.indexOf("x") == 0).count());



回答2:


Let’s say you’re trying to debug a pipeline of operations in a stream you could use forEach to print or log the result of a stream.

This is where the stream operation peek can help. Its purpose is to execute an action on each element of a stream as it’s consumed. But it doesn’t consume the whole stream like forEach does; it forwards the element it performed an action on to the next operation in the pipeline.

In your case it should you like this.

List<String> genre = new ArrayList<String>(Arrays.asList("rock", "pop", 
"jazz","reggae"));
   genre.stream()
       .peek(s -> System.out.println("from stream:" + s))
       .map(x -> x.replace("r", "x"))
       .peek(s -> System.out.println("from replace stream:" + s))
       .filter(y -> y.indexOf("y") == 0)
       .peek(s -> System.out.println("from stream:" + s ))
       .collect(toList());


来源:https://stackoverflow.com/questions/46975371/in-java-why-stream-peek-is-not-working-for-me

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