Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Streams peek api

Tags:

java

java-8

I tried the following snippet of Java 8 code with peek.

List<String> list = Arrays.asList("Bender", "Fry", "Leela"); list.stream().peek(System.out::println); 

However there is nothing printed out on the console. If I do this instead:

list.stream().peek(System.out::println).forEach(System.out::println); 

I see the following which outputs both the peek as well as foreach invocation.

Bender Bender Fry Fry Leela Leela 

Both foreach and peek take in a (Consumer<? super T> action) So why is the output different?

like image 492
Neo Avatar asked Apr 12 '15 04:04

Neo


People also ask

What is peek in stream API?

Description. Stream peek() method is an intermediate operation. It returns a Stream consisting of the elements of current stream. It additionally perform the provided action on each element as elements.

What does the Peek () method do when should you use it?

peek() method in Java is used to retrieve or fetch the first element of the Stack or the element present at the top of the Stack. The element retrieved does not get deleted or removed from the Stack. Parameters: The method does not take any parameters.

What is difference between Peek and foreach?

(1): using stream. foreach, you can also change the internal property value of each item in the list, etc., but you need to perform "secondary flow processing" to get the smallest item in the list (filter according to age). (2): stream. peek can get the smallest item directly compared with stream.

Is stream API introduced in Java 8?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.


2 Answers

The Javadoc mentions the following:

Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.

peek being an intermediate operation does nothing. On applying a terminal operation like foreach, the results do get printed out as seen.

like image 179
Neo Avatar answered Sep 22 '22 02:09

Neo


The documentation for peek says

Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This is an intermediate operation.

You therefore have to do something with the resulting stream for System.out.println to do anything.

like image 34
Paul Boddington Avatar answered Sep 23 '22 02:09

Paul Boddington