📜  Java中的 DoubleStream peek() 示例

📅  最后修改于: 2022-05-13 01:55:39.514000             🧑  作者: Mango

Java中的 DoubleStream peek() 示例

DoubleStream peek()Java.util.stream.DoubleStream中的一个方法。该函数返回一个由该流的元素组成的流,在从结果流中消耗元素时,另外对每个元素执行提供的操作。

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

句法 :

DoubleStream peek(DoubleConsumer action) 

参数 :

  1. DoubleStream :原始双值元素的序列。
  2. 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