DoubleStream peek() in Java with examples
Last Updated :
06 Dec, 2018
DoubleStream peek() is a method in java.util.stream.DoubleStream. 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.
DoubleStream peek() is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.
Syntax :
DoubleStream peek(DoubleConsumer action)
Parameters :
- DoubleStream : A sequence of primitive double-valued elements.
- DoubleConsumer : Represents an operation that accepts a single double-valued argument and returns no result.
Return Value : the function returns a parallel DoubleStream.
Note : This method exists mainly to support debugging.
Example 1 : Performing sum operation to find sum of elements of given DoubleStream.
import java.util.*;
import java.util.stream.DoubleStream;
class GFG {
public static void main(String[] args)
{
DoubleStream stream =
DoubleStream.of( 2.2 , 3.3 , 4.5 , 6.7 );
double sum = stream.peek(System.out::println).sum();
System.out.println( "sum is : " + sum);
}
}
|
Output:
2.2
3.3
4.5
6.7
sum is : 16.7
Example 2 : Performing count operation on elements of given DoubleStream.
import java.util.*;
import java.util.stream.DoubleStream;
class GFG {
public static void main(String[] args)
{
DoubleStream stream =
DoubleStream.of( 2.2 , 3.3 , 4.5 , 6.7 );
long Count = stream.peek(System.out::println).count();
System.out.println( "count : " + Count);
}
}
|
Output:
2.2
3.3
4.5
6.7
count : 4
Example 3 : Performing average operation on elements of given DoubleStream.
import java.util.*;
import java.util.OptionalDouble;
import java.util.stream.DoubleStream;
class GFG {
public static void main(String[] args)
{
DoubleStream stream =
DoubleStream.of( 2.2 , 3.3 , 4.5 , 6.7 );
;
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.2
3.3
4.5
6.7
Average is : 4.175
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...