StreamAPI中如何避免重复消费同一个stream的代码实例?
- 内容介绍
- 文章标签
- 相关推荐
本文共计336个文字,预计阅读时间需要2分钟。
在StreamAPI中,stream不能被重复消费。一旦被使用,stream就被关闭了。例如,如果stream被消费了,再次尝试消费它就会抛出IllegalStateException:stream has already been operated upon or closed。比如下面的代码中,stream被消费了:
javaStream stream=Arrays.stream(new Integer[]{1, 2, 3});stream.forEach(System.out::println);// 再次调用stream.forEach会抛出异常stream.forEach(System.out::println);
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); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。
本文共计336个文字,预计阅读时间需要2分钟。
在StreamAPI中,stream不能被重复消费。一旦被使用,stream就被关闭了。例如,如果stream被消费了,再次尝试消费它就会抛出IllegalStateException:stream has already been operated upon or closed。比如下面的代码中,stream被消费了:
javaStream stream=Arrays.stream(new Integer[]{1, 2, 3});stream.forEach(System.out::println);// 再次调用stream.forEach会抛出异常stream.forEach(System.out::println);
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); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

