IntStream peek() method in Java

Java 8ProgrammingObject Oriented Programming

The peek() method in the IntStream class in Java returns a stream consisting of the elements of this stream. It additionally performs the provided action on each element as elements are consumed from the resulting stream.

The syntax is as follows

IntStream peek(IntConsumer action)

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

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

Example

 Live Demo

import java.util.*;
import java.util.stream.IntStream;
public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.range(50, 60);
      System.out.println("Elements in the stream = ");
      long res = intStream.peek(System.out::println).count();
      System.out.println("Count of elements = " + res);
   }
}

Output

Elements in the stream =
50
51
52
53
54
55
56
57
58
59
Count of elements = 10
raja
Published on 26-Mar-2019 12:16:00
Advertisements