Java DoubleStream peek()方法及示例
DoubleStream peek() 是 java.util.stream.DoubleStream 中的一个方法 。 该函数返回一个由该流的元素组成的流,另外,当元素从产生的流中被消耗时,对每个元素执行所提供的操作。
DoubleStream peek()是一个 中间操作。 这些操作始终是懒惰的。中间操作是在一个流实例上调用的,在它们完成处理后,会给出一个流实例作为输出:
语法:
DoubleStream peek(DoubleConsumer action)
参数
- DoubleStream : 一个原始双值元素的序列。
- DoubleConsumer : 代表一个接受单一双值参数的操作,不返回结果。
返回值: 该函数返回一个并行的DoubleStream。
注意: 这个方法的存在主要是为了支持调试。
例子 1 : 执行求和操作,找出给定的DoubleStream中的元素之和。
// Java code for DoubleStream peek()
// where the action performed is to get
// sum of all elements.
import java.util.*;
import java.util.stream.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a stream of doubles
DoubleStream stream =
DoubleStream.of(2.2, 3.3, 4.5, 6.7);
// performing action sum on elements of
// given range and storing the result in sum
double sum = stream.peek(System.out::println).sum();
// Displaying the result of action performed
System.out.println("sum is : " + sum);
}
}
输出:
2.2
3.3
4.5
6.7
sum is : 16.7
例2: 对给定的DoubleStream的元素进行计数操作。
// Java code for DoubleStream peek()
// where the action performed is to get
// count of all elements in given range
import java.util.*;
import java.util.stream.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a stream of doubles
DoubleStream stream =
DoubleStream.of(2.2, 3.3, 4.5, 6.7);
// performing count operation on elements of
// given DoubleStream and storing the result in Count
long Count = stream.peek(System.out::println).count();
// Displaying the result of action performed
System.out.println("count : " + Count);
}
}
输出:
2.2
3.3
4.5
6.7
count : 4
例3: 对给定的DoubleStream的元素进行平均操作。
// Java code for DoubleStream peek()
// where the action performed is to get
// average of all elements.
import java.util.*;
import java.util.OptionalDouble;
import java.util.stream.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a stream of doubles
DoubleStream stream =
DoubleStream.of(2.2, 3.3, 4.5, 6.7);
;
// performing action "average" on elements of
// given DoubleStream and storing the result in avg
OptionalDouble avg = stream.peek(System.out::println)
.average();
// If a value is present, isPresent()
// will return true, else -1 is displayed.
if (avg.isPresent()) {
System.out.println("Average is : " + avg.getAsDouble());
}
else {
System.out.println("-1");
}
}
}
输出:
2.2
3.3
4.5
6.7
Average is : 4.175