0

I have below code, but gettting error:

Stream<BigDecimal> method(Stream<BigDecimal> in) {
    if (in == null)
        return Stream.empty();

    Supplier<Stream<BigDecimal>> supplier = () -> in;
    
    Stream<BigDecimal> s1 = supplier.get().filter(e -> e != null);
    long count = s1.count();
    

    double average = supplier.get().mapToDouble(BigDecimal::doubleValue).average().orElse(Double.NaN);
    
    return supplier.get();
}

Error says:

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
    at java.util.stream.AbstractPipeline.<init>(AbstractPipeline.java:203)
    at java.util.stream.DoublePipeline.<init>(DoublePipeline.java:90)
    at java.util.stream.DoublePipeline$StatelessOp.<init>(DoublePipeline.java:597)
    at java.util.stream.ReferencePipeline$6.<init>(ReferencePipeline.java:238)
    at java.util.stream.ReferencePipeline.mapToDouble(ReferencePipeline.java:237)

How to fix this issue, I already tried using supplier.get method, but still getting errors.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
learner
  • 6,062
  • 14
  • 79
  • 139

1 Answers1

0

You're not really using the Supplier here. If you want this to work, the argument to method must itself be a Supplier<Stream<BigDecimal>>. () -> in doesn't actually do what you need the supplier to do, which is to generate an entirely new stream.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413