2

Im trying to perform an operation and add those values in int[].

I collected those values in Stream, but while printing those values, im getting exception that stream is closed.

My Code below:

import java.util.*;
import java.util.stream.*;
import java.util.function.Supplier;
public class Main
{
  public static void main (String[]args)
  {
    IntStream mystream = IntStream.of (3, 4, 5, 9, 18, 54, 8, 7, 14, 3);
      Stream < int[] > p =
      mystream.boxed ().flatMap (a->mystream.mapToObj (b->{
                               return new int[]{a, b,
                                    (int)
                                    Math.
                                    sqrt ((a * a) + (b * b))};}));

    Supplier < Stream < int[] >> streamSupplier = ()->p;

    streamSupplier.get ().forEach (t->System.out.
                         println (t[0] + ", " + t[1] +
                              ", " + t[2]));
  }
}

Below is the error im getting: enter image description here

2 Answers2

3

You are trying to consume the IntStream referenced by mystream multiple times.

The following will eliminate the error:

Stream<int[]> p =
    mystream.boxed ()
            .flatMap (a->IntStream.of (3, 4, 5, 9, 18, 54, 8, 7, 14, 3)
                                  .mapToObj (b->new int[]{a, b, (int) Math.sqrt (a*a + b*b)}));

That said, I'd also eliminate your Supplier<Stream<int[]>> instance, and operate on the p Stream directly (i.e. p.forEach(...)), since it can be consumed only once, so there's no point in wrapping it with a Supplier.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

You are only allowed to perform a single operation that consumes a Stream, otherwise, you will get an exception that states that the Stream has already been operated upon or closed.

Here is how you can fix it (with some refactoring):

List<Integer> integerList = List.of(3, 4, 5, 9, 18, 54, 8, 7, 14, 3);
int[] ints = new int[]{3, 4, 5, 9, 18, 54, 8, 7, 14, 3};
IntStream mystream = IntStream.of(ints);
Stream<int[]> p =
    mystream.boxed().flatMap(a -> integerList.stream().map(b ->
        new int[]{a, b, (int) Math.sqrt((a * a) + (b * b))}
    ));

p.forEach(t -> System.out.println(t[0] + ", " + t[1] + ", " + t[2]));
Piotr Niewinski
  • 1,298
  • 2
  • 15
  • 27