Java Stream.Builder add()方法

来源:这里教程网 时间:2026-02-17 21:12:13 作者:

Java Stream.Builder add()方法

Stream.Builder add(T t)用于在流的构建阶段向元素中插入一个元素。它将一个元素添加到正在构建的流中。

语法

default Stream.Builder<T> add(T t)

参数。该方法添加了一个强制性参数 t ,它是要输入到流中的元素。

异常: 该方法抛出 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 builtGeeksforGeeksforGeeksData StructuresGeeks 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 built56789Exception thrown when now adding element into the stream: java.lang.IllegalStateException

相关推荐