Stream.Builder add(T t)用於在流的構建階段將元素插入到元素中。它將元素添加到正在構建的流中。
用法:
default Stream.Builder<T> add(T t)
參數:此方法添加了強製參數t,該參數是要輸入到流中的元素。
Exceptions:當構建器已經轉換到構建狀態時,此方法引發IllegalStateException :。這表示流已進入構建階段,現在不能更改。因此,無法將更多元素添加到流中。
下麵是說明add()方法的示例:
範例1:
// Java code to show the implementation
// of Stream.Builder add(T t)
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Declaring an empty Stream
Stream.Builder<String> str_b = Stream.builder();
// Inserting elements into the stream
// using Stream.Builder add(T t)
str_b.add("Geeks");
str_b.add("for");
str_b.add("GeeksforGeeks");
str_b.add("Data Structures");
str_b.add("Geeks Classes");
// Creating the String Stream
// The stream has now entered the built phase
Stream<String> s = str_b.build();
// printing the elements
System.out.println("Stream successfully built");
s.forEach(System.out::println);
}
}
輸出:
Stream successfully built Geeks for GeeksforGeeks Data Structures Geeks Classes
範例2:為了說明IllegalStateException
// Java code to show the implementation
// of Stream.Builder add(T t)
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Declaring an empty Stream
Stream.Builder<String> str_b = Stream.builder();
// using Stream.Builder add(T t)
str_b.add("5");
str_b.add("6");
str_b.add("7");
str_b.add("8");
str_b.add("9");
// Creating the String Stream
// The stream has now entered the built phase
Stream<String> s = str_b.build();
// printing the elements
System.out.println("Stream successfully built");
s.forEach(System.out::println);
// Trying to add another element into the stream
// Since the Stream is in built phase
// This operation is not possible now
// Hence add() will throw exception now
try {
str_b.add("50");
}
catch (Exception e) {
System.out.println("Exception thrown "
+ "when now adding element into the stream:"
+ e);
}
}
}
輸出:
Stream successfully built 5 6 7 8 9 Exception thrown when now adding element into the stream:java.lang.IllegalStateException
相關用法
- Java Java lang.Long.lowestOneBit()用法及代碼示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代碼示例
- Java Java lang.Long.highestOneBit()用法及代碼示例
- Java Java.util.Collections.rotate()用法及代碼示例
- Java Java lang.Long.byteValue()用法及代碼示例
- Java Java lang.Long.numberOfTrailingZeros()用法及代碼示例
- Java Java lang.Long.reverse()用法及代碼示例
- Java Java lang.Long.builtcount()用法及代碼示例
- Java Java.util.Collections.disjoint()用法及代碼示例
- Java Clock withZone()用法及代碼示例
- Java Java.lang.string.replace()用法及代碼示例
- Java Java.util.ArrayList.addall()用法及代碼示例
- Java Clock tickMinutes()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Stream.Builder add() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。