In this code, a list of integers integers is created containing the elements 0, 1, and 2. A stream is then created from this list, and the following operations are performed in sequence:
peek(System.out::print):
The peek method is an intermediate operation that allows performing an action on each element as it is encountered in the stream. In this case, System.out::print is used to print each element. However, since peek is intermediate, the printing occurs only when a terminal operation is executed.
limit(2):
The limit method is another intermediate operation that truncates the stream to contain no more than the specified number of elements. Here, it limits the stream to the first 2 elements.
forEach(i -> {}):
The forEach method is a terminal operation that performs the given action on each element of the stream. In this case, the action is an empty lambda expression (i -> {}), which does nothing for each element.
The sequence of operations can be visualized as follows:
Original Stream Elements: 0, 1, 2
After peek(System.out::print): Elements are printed as they are encountered.
After limit(2): Stream is truncated to 0, 1.
After forEach(i -> {}): No additional action; serves to trigger the processing.
Therefore, the output of the code is 01, corresponding to the first two elements of the list being printed due to the peek operation.
[Reference:, Stream.peek() Method in Java with Examples - GeeksforGeeks]
Contribute your Thoughts:
Chosen Answer:
This is a voting comment (?). You can switch to a simple comment. It is better to Upvote an existing comment if you don't have anything to add.
Submit