📜  Java中的 DoubleStream.Builder accept() 方法

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

Java中的 DoubleStream.Builder accept() 方法

DoubleStream.Builder accept(double t)用于在流的构建阶段将元素插入到元素中。它接受正在构建的流的元素。

句法:

void accept(double t)

参数:此方法接受一个强制参数t ,它是要输入到流中的元素。

异常:当构建器已经转换到构建状态时,此方法会抛出IllegalStateException 。这意味着流已进入构建阶段,现在不能更改。因此,不能将更多元素接受到流中。

以下是说明 accept() 方法的示例:

示例 1:

// Java code to show the implementation
// of DoubleStream.Builder accept(double t)
  
import java.util.stream.DoubleStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Declaring an empty Stream
        DoubleStream.Builder b = DoubleStream.builder();
  
        // Inserting elements into the stream
        // using DoubleStream.Builder accept(double t)
        b.accept(45.54);
        b.accept(415.2541);
        b.accept(12.21);
        b.accept(778);
  
        // Creating the Stream
        // The stream has now entered the built phase
        // printing the elements
        System.out.println("Stream successfully built");
        b.build().forEach(System.out::println);
    }
}
输出:
Stream successfully built
45.54
415.2541
12.21
778.0

示例 2:说明 IllegalStateException

// Java code to show the implementation
// of DoubleStream.Builder accept(double t)
  
import java.util.stream.DoubleStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Declaring an empty Stream
        DoubleStream.Builder b = DoubleStream.builder();
  
        // using DoubleStream.Builder accept(double t)
        b.accept(45.54);
        b.accept(415.2541);
        b.accept(12.21);
        b.accept(778);
  
        // Creating the Stream
        // The stream has now entered the built phase
        // printing the elements
        System.out.println("Stream successfully built");
        b.build().forEach(System.out::println);
  
        // Trying to accept another element into the stream
        // Since the Stream is in built phase
        // This operation is not possible now
        // Hence accept() will throw exception now
  
        try {
            b.accept(75.1452);
        }
        catch (Exception e) {
            System.out.println("Exception thrown "
                               + "when now accepting element into the stream: "
                               + e);
        }
    }
}
输出:
Stream successfully built
45.54
415.2541
12.21
778.0
Exception thrown when now accepting element into the stream: java.lang.IllegalStateException