我正在尝试使用Java8流计算素数,但是我遇到了IllegalStateException:流已被操作或关闭。
这是我的代码:
package experimentations.chapter02;
import java.util.stream.Stream;
public class PrimesStream {
public static void main(String[] args) {
Stream.iterate(0, e-> e+1).filter(PrimesStream::isPrime).limit(10).forEach(System.out::println);
}
public static boolean isPrime(int i){
if (i < 2) return false;
Stream<Integer> stream = Stream.iterate(2, e -> e+1);
stream.limit(i - 2);
return !stream.anyMatch(divisor -> i%divisor == 0);
}
}
这是stacktrace:
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:229)
at java.util.stream.ReferencePipeline.anyMatch(ReferencePipeline.java:449)
at experimentations.chapter02.PrimesStream.isPrime(PrimesStream.java:14)
at experimentations.chapter02.PrimesStream$$Lambda$2/918221580.test(Unknown Source)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
at java.util.Spliterators$IteratorSpliterator.tryAdvance(Spliterators.java:1812)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:529)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:516)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at experimentations.chapter02.PrimesStream.main(PrimesStream.java:7)
我感觉这是因为我试图将流调用应用于另一个,但是即使有这种想法,我也不知道什么是最简单的解决方法。
最佳答案
您需要链接流方法,将其修复,因此您的isPrime
应该类似于:
return !Stream.iterate(2, e -> e + 1)
.limit(i - 1)
.anyMatch(divisor -> i % divisor == 0);