📜  Java中的 LongStream.Builder 构建()

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

Java中的 LongStream.Builder 构建()

LongStream.Builder build() 构建流,将此构建器转换为构建状态

句法 :

LongStream build()

返回值:此方法返回构建的流。

注意:流构建器有一个生命周期,从构建阶段开始,在此期间可以添加元素,然后过渡到构建阶段,之后可能无法添加元素。构建阶段从调用 build() 方法开始,该方法创建一个有序流,其元素是按添加顺序添加到流构建器的元素。

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

示例 1:

// Java code to show the implementation
// of LongStream.Builder build()
  
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a Stream in building phase
        LongStream.Builder b = LongStream.builder();
  
        // Adding elements into the stream
        b.add(1L);
        b.add(2L);
        b.add(3L);
        b.add(4L);
  
        // Constructing the built stream using build()
        // This will enter the stream in built phase
        b.build().forEach(System.out::println);
    }
}
输出:
1
2
3
4

示例 2:在调用 build() 方法后尝试添加元素(当流处于构建阶段时)。

// Java code to show the implementation
// of LongStream.Builder build()
  
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating a Stream in building phase
        LongStream.Builder b = LongStream.builder();
  
        // Adding elements into the stream
        b.add(1L);
        b.add(2L);
        b.add(3L);
        b.add(4L);
  
        // Constructing the built stream using build()
        // This will enter the stream in built phase
        // Now no more elements can be added to this stream
        b.build().forEach(System.out::println);
  
        // Trying to add more elements in built phase
        // This will cause exception
        try {
            b.add(50L);
        }
        catch (Exception e) {
            System.out.println("\nException: " + e);
        }
    }
}
输出:
1
2
3
4

输出:

1
2
3
4

Exception: java.lang.IllegalStateException