Java IntStream.Builder build()示例

Java IntStream.Builder build()示例

IntStream.Builder build() 构建流,将此构建器过渡到构建状态。

语法

IntStream build()

返回值: 该方法返回建立的流。

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

下面是说明build()方法的例子。

例1 :

// Java code to show the implementation
// of IntStream.Builder build()
  
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a Stream in building phase
        IntStream.Builder b = IntStream.builder();
  
        // Adding elements into the stream
        b.add(1);
        b.add(2);
        b.add(3);
        b.add(4);
  
        // 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 IntStream.Builder build()
  
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating a Stream in building phase
        IntStream.Builder b = IntStream.builder();
  
        // Adding elements into the stream
        b.add(1);
        b.add(2);
        b.add(3);
        b.add(4);
  
        // 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(50);
        }
        catch (Exception e) {
            System.out.println("\nException: " + e);
        }
    }
}

输出。

1
2
3
4

Exception: java.lang.IllegalStateException

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程