Search code examples
javaexceptionfilterjava-8java-stream

Stream has already been operated upon or closed - Java 8


Why I have next exception?

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.<init>(AbstractPipeline.java:203)...
com.search.offer.OffersSelector.isGood(OffersSelector.java:23)

How change the code to fix it?

Stream<String> titleExclusions = ResourceUtility.contentToUtf8TreeSet("+.txt").
        stream().filter(item -> item.length() == 0).collect(Collectors.toSet()).stream();
//...
titleExclusions.filter(tittle::contains).collect(Collectors.toSet()).size() == 0;//line 23

Solution

  • You can't operate on Streams more than once so you are better off using Collections as these can be used more than once.

    Set<String> titleExclusions = ResourceUtility.contentToUtf8TreeSet("+.txt")
                                                 .stream()
                                                 .filter(item -> !item.isEmpty())
                                                 .collect(Collectors.toSet());
    // uses titleExclusions 
    boolean noMatches = titleExclusions.stream()
                                       .noneMatch(tittle::contains);
    // uses titleExclusions again.
    

    Note: I assume you wanted the non-blank lines from your source file instead of the sets of blank ones. filter takes a Predicate of what is retained rather than what is discarded.

    Thank you @Holger for simplifying the second statement.