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());
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());
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With