LongStream peek() method in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 27-Mar-2019 09:59:44
Advertisements