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
相關用法
- Java Locale.Builder build()用法及代碼示例
- Java Java lang.Long.reverse()用法及代碼示例
- Java Java lang.Long.builtcount()用法及代碼示例
- Java Java.util.concurrent.RecursiveAction用法及代碼示例
- Java Java.util.concurrent.Phaser用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 IntStream.Builder build() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。