双流。Java中的Builder add(双t)及其示例

双流。建筑商添加(双t) 用于在流的构建阶段将图元插入到图元中。它向正在构建的流中添加一个元素。

null

语法:

default DoubleStream.Builder add(double t)

参数: 此方法接受一个强制参数 T 这是要输入到流中的元素。

例外情况: 这个方法抛出 非法州例外: 当构建器已转换为已构建状态时。这意味着流已经进入了构建阶段,现在不能更改。因此,不能向流中添加更多元素。

下面是示例来说明add()方法:

例1:

// Java code to show the implementation
// of DoubleStream.Builder add(double t)
import java.util.stream.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Declaring an empty Stream
DoubleStream.Builder b = DoubleStream.builder();
// Inserting elements into the stream
// using DoubleStream.Builder add(double t)
b.add( 4.4 );
b.add( 5.84 );
b.add( 6 );
b.add( 7.47 );
// Creating the Stream
// The stream has now entered the built phase
// printing the elements
System.out.println( "Stream successfully built" );
b.build().forEach(System.out::println);
}
}


输出:

Stream successfully built
4.4
5.84
6.0
7.47

例2: 来说明非法的例外情况

// Java code to show the implementation
// of DoubleStream.Builder add(T t)
import java.util.stream.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Declaring an empty Stream
DoubleStream.Builder b = DoubleStream.builder();
// using DoubleStream.Builder add(T t)
b.add( 4.7 );
b.add( 5.9 );
b.add( 6 );
b.add( 7.785 );
// Creating the Stream
// The stream has now entered the built phase
// printing the elements
System.out.println( "Stream successfully built" );
b.build().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 {
b.add( 50.784 );
}
catch (Exception e) {
System.out.println( "Exception thrown "
+ "when now adding element into the stream: "
+ e);
}
}
}


输出:

Stream successfully built
4.7
5.9
6.0
7.785
Exception thrown when now adding element into the stream: java.lang.IllegalStateException

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享