Java中的DoubleStream peek()及其示例

双流peek() 这是一种 JAVAutil。流动双流 。该函数返回一个由该流的元素组成的流,在从结果流中消耗元素时,对每个元素执行提供的操作。

null

DoubleStream peek()是一个 中间操作 .这些操作总是懒惰的。在流实例上调用中间操作,完成处理后,它们将流实例作为输出。

语法:

DoubleStream peek(DoubleConsumer action) 

参数:

  1. 双流: 一个原始的双值元素序列。
  2. 双重消费者: 表示接受单个双值参数且不返回结果的操作。

返回值: 该函数返回一个并行双流。

注: 这种方法的存在主要是为了支持调试。

例1: 执行求和运算以查找给定双流的元素之和。

// 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

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享