Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()); 
like image 420
Kaustubh_Kharche Avatar asked Jan 30 '23 08:01

Kaustubh_Kharche


2 Answers

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());
like image 55
davidxxx Avatar answered Feb 03 '23 23:02

davidxxx


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());
like image 33
nyulan Avatar answered Feb 03 '23 21:02

nyulan