javastreamjava-streamsupplier

JAVA-STREAM : re-use double a DoubleStream


I need a trick to solve this problem i'm using Java 1.8 And I retrieved a an object from a method that returns a DoubleStream object. So, the problem is I could not reuse the stream after it has been consumed.

Here is the first version of the code :

 DoubleStream stream = object.getvalueStream(a,b);
 if(condtion)
   stream.map(v -> v * 2);
 stream.forEach(value -> {
        // do something
  }

The problem is that once the condition is true, the stream is consumed And I can not reuse it. So I tried to use a supplier to return a doubleStream from supplier and iterate overt it.

But still the same problem as I try to recover the stream from my stream object which is already used.

Here is my updated code :

      DoubleStream stream = object.getvalueStream(a,b);
      if(condtion)
      stream.map(v -> v * 2);
      Supplier>DoubleStream> streamSupplier = () -> DoubleStream.of(stream.toArray());
      streamSupplier.get().forEach(value -> {
           //Do something

But I still have the same problem since I create my supplier from my stream already used if the condition is true.

Thanks for your help.


Solution

  • once the condition is true, the stream is consumed And I can not reuse it

    Intermediate operations (e.g. map) return a new stream, so you need to reassign the stream after the intermediate operation (map).

    I.e.

    DoubleStream stream = object.getvalueStream(a,b);
    if (condition) {
        stream = stream.map(v -> v * 2);
    }
    stream.forEach(value -> {
        // do something
    }
    

    Note terminal operations (e.g. foreach) do not return a stream. So if you want many terminal operations, you should collect the stream so it can be reused.

    Note also, there is also an intermediate version of foreach called peek if you wish to chain foreach (peek) calls.