-1

I have this snippet:

    final Stream<String>stream = getStream().filter(a->StringUtils.contains(a,"http"));
    stream.filter(a->true);//LINE PROBLEM I JUST THOUGHT THAT THIS WOULD  JUST IGNORE
    System.out.println(stream.count());

But throws:

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed

I know that streams can be used just once but what is wrong with this line? It's consuming the stream?

stream.filter(a->true);//NOT A TERMINAL OPERATION A INTERMEDIATE OPERATION

If I ripped it of just use my code like this

System.out.println(stream.filter(a->true).count());

Not exception is thrown.

If I use this code NotException is Thrown.

    Stream<String>stream = getStream().filter(a->StringUtils.contains(a,"http"));
    stream = stream.filter(a->true);
    System.out.println(stream.count());

But why filter is throwing exception and IS NOT A TERMINAL OPERATION?

I am using just the simplest code to get the idea.

I am using Netbeans 8.2 with Java 8 update 122 also tested in Intellij Idea 2018 Ultimate.

halfer
  • 19,824
  • 17
  • 99
  • 186
chiperortiz
  • 4,751
  • 9
  • 45
  • 79
  • Is this request stream? OverrideHttpinputmessage and httpmessageconverter and then use IOUtils.toString() to convert stream as string then use lambda expression. – sankar Feb 28 '19 at 13:17
  • is just a example.. to represent the idea. – chiperortiz Feb 28 '19 at 13:32

1 Answers1

2

According to Stream javadoc:

A stream should be operated on (invoking an intermediate or terminal stream operation) only once. This rules out, for example, "forked" streams, where the same source feeds two or more pipelines, or multiple traversals of the same stream. A stream implementation may throw IllegalStateException if it detects that the stream is being reused. However, since some stream operations may return their receiver rather than a new stream object, it may not be possible to detect reuse in all cases.

To avoid this, you can use Stream.Builder

See also Copy a stream to avoid "stream has already been operated upon or closed"

Ruslan
  • 6,090
  • 1
  • 21
  • 36