以下
java 8流没有任何终端操作.下面的块不应该是懒惰的,因为我只有中间操作并且还没有通过终端操作进行操作.当我运行这个块时,我得到“流已经被操作或关闭”.见
https://ideone.com/naR7GB
Stream<String> s = Stream.of("A","B"); s.map(String::toUpperCase); s.map(String::toLowerCase);
堆栈跟踪:
java.lang.IllegalStateException: stream has already been operated upon or closed at java.util.stream.AbstractPipeline.<init>(AbstractPipeline.java:203) at java.util.stream.ReferencePipeline.<init>(ReferencePipeline.java:94) at java.util.stream.ReferencePipeline$StatelessOp.<init>(ReferencePipeline.java:618) at java.util.stream.ReferencePipeline$3.<init>(ReferencePipeline.java:187) at java.util.stream.ReferencePipeline.map(ReferencePipeline.java:186)
解决方法
您需要将第二个map()应用于映射的实例:
s.map(String::toUpperCase).map(String::toLowerCase);
要么
Stream<String> s = Stream.of("A","B"); Stream<String> s2 = s.map(String::toUpperCase); Stream<String> s3 = s2.map(String::toLowerCase);
因为您只能对同一个流实例执行1次操作.
但请记住,你只能消耗一次!因此,要么消耗s2或s3,就不能同时消耗两者.这就是我们通常编写链式调用的原因,因为保留中间对象没有意义.