Java 8流IllegalStateException

时间:2014-04-07 16:39:41

标签: java java-8 java-stream

我正在尝试使用Java8流计算Prime数字,但是我遇到了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);
    }

}

这是堆栈跟踪:

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)

我觉得这是因为我试图将一个流调用应用到另一个,但即使有了这个想法,我也不知道什么是最简单的解决方法。

2 个答案:

答案 0 :(得分:2)

你需要链接你的流方法,这将修复它,所以你的isPrime应该是这样的:

return !Stream.iterate(2, e -> e + 1)
    .limit(i - 1)
    .anyMatch(divisor -> i % divisor == 0);

答案 1 :(得分:0)

以下是导致此异常的示例代码。

List<Person> people = Arrays.asList(
 new Person("Bob", 17),
 new Person("Dave", 23),
 new Person("Joe", 32));

Stream<String> nameStream = people.stream()
 .filter(person -> person.getAge() > 21)
 .map(Person::getName);

nameStream.forEach(System.out::println);

// When stream values are gone, they are gone. Let’s try again: 
nameStream.forEach(System.out::println); 

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.forEach(ReferencePipeline.java:418)

因此,您只能在流上最多执行一项操作

检查this以获取有关java8功能的更多信息。