LongStream peek() method in Java


The peek() method of the LongStream class returns a stream with the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.

The syntax is as follows −

LongStream peek(LongConsumer action)

Here, LongConsumer represents an operation that accepts a single long-valued argument and returns no result. The action parameter is a non-interfering action to perform on the elements as they are consumed from the stream.

To use the LongStream class in Java, import the following package −

import java.util.stream.LongStream;

The following is an example to implement LongStream peek() method in Java

Example

 Live Demo

import java.util.stream.LongStream;
public class Demo {
   public static void main(String[] args) {
      LongStream longStream = LongStream.range(30L, 40L);
      System.out.println("Elements in the stream = ");
      long numEle = longStream.peek(System.out::println).count();
      System.out.println("The number of elements in the stream = " + numEle);
   }
}

Output

Elements in the stream =
30
31
32
33
34
35
36
37
38
39
The number of elements in the stream = 10

Updated on: 30-Jul-2019

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements