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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
06 Dec, 2018
Like Article
Save Article