软件编程
位置:首页>> 软件编程>> java编程>> StreamAPI多次消费一个stream代码实例

StreamAPI多次消费一个stream代码实例

作者:JaxYoun  发布时间:2023-10-15 19:44:09 

标签:API,消费,stream

StreamAPI中的stream不能被重复消费,一旦它被使用,stream就被关闭了,别的地方再消费它就会抛IllegalStateException:stream has already been operated upon or closed。

比如下面的代码中,stream被消费了两次,第二次消费时将会抛异常:


@Test
public void statistics() {
 IntStream range = IntStream.range(0, 12);

OptionalInt min = range.min(); //第一次消费正常
 System.out.println(min);

long count = range.count(); //第二次消费将报错
 System.out.println(count);
}

如何实在需要多次消费呢,通过Supplier来生产stream,每次调用supplier.get()获取一个崭新的stream对象,虽然对象是新的,但是每个stream中的数据是相同的,间接地实现了重复消费的语义:


@Test
public void statistics0() {
 Supplier<IntStream> supplier= () -> IntStream.range(0, 12);

OptionalInt min = supplier.get().min(); //第一次消费正常
 System.out.println(min);

long count = supplier.get().count(); //第二次消费正常
 System.out.println(count);
}

来源:https://www.cnblogs.com/JaxYoun/p/12549661.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com