IntStream peek() in Java with examples
Last Updated :
06 Dec, 2018
IntStream peek() is a method in java.util.stream.IntStream. The function 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.
Syntax :
IntStream peek(IntConsumer action)
Where, IntStream is a sequence of primitive
int-valued elements and the function returns
a parallel IntStream and IntConsumer represents
an operation that accepts a single int-valued argument.
Example 1 : Performing sum on a stream of given range.
import java.util.*;
import java.util.stream.IntStream;
class GFG {
public static void main(String[] args) {
IntStream stream = IntStream.range(2, 10);
int sum = stream.peek(System.out::println).sum();
System.out.println("sum is : " + sum);
}
}
|
Output :
2
3
4
5
6
7
8
9
sum is : 44
Example 2 : Performing count operation on a stream of given range.
import java.util.*;
import java.util.stream.IntStream;
class GFG {
public static void main(String[] args) {
IntStream stream = IntStream.range(2, 10);
long Count = stream.peek(System.out::println).count();
System.out.println("count : " + Count);
}
}
|
Output :
2
3
4
5
6
7
8
9
count : 8
Example 3 : Performing Average operation on a stream of given range.
import java.util.*;
import java.util.OptionalDouble;
import java.util.stream.IntStream;
class GFG {
public static void main(String[] args) {
IntStream stream = IntStream.range(2, 10);
OptionalDouble avg = stream.peek(System.out::println)
.average();
if(avg.isPresent())
{
System.out.println("Average is : " + avg.getAsDouble());
}
else
{
System.out.println("-1");
}
}
}
|
Output :
2
3
4
5
6
7
8
9
Average is : 5.5
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...