LongStream peek() in Java with examples
Last Updated :
06 Dec, 2018
LongStream peek() is a method in java.util.stream.LongStream. 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 :
LongStream peek(LongConsumer action)
Where, LongStream is a sequence of primitive
long-valued elements and the function returns
a parallel LongStream and LongConsumer represents
an operation that accepts a single long-valued argument.
Example 1 : Performing sum on a stream of given range.
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
LongStream stream = LongStream.range(2L, 10L);
long 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.LongStream;
class GFG {
public static void main(String[] args)
{
LongStream stream = LongStream.range(2L, 10L);
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.LongStream;
class GFG {
public static void main(String[] args)
{
LongStream stream = LongStream.range(2L, 10L);
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...