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


Java Stream.Builder add()用法及代码示例


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


相关用法


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