java double add,Java DoubleStream.Builder add(double t)用法及代码示例

DoubleStream.Builder add(double t)用于在流的构建阶段将元素插入到元素中。它将元素添加到正在构建的流中。

用法:

default DoubleStream.Builder add(double t)

参数:此方法接受强制参数t,该参数是要输入到流中的元素。

Exceptions:当构建器已经转换到构建状态时,此方法引发IllegalStateException :。这表示流已进入构建阶段,现在不能更改。因此,无法将更多元素添加到流中。

下面是说明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:为了说明IllegalStateException

// 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值