当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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


相关用法


注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 IntStream.Builder build() in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。