Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8132367

Alternatives to terminal operations for the Stream API

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Won't Fix
    • Icon: P4 P4
    • None
    • 9
    • core-libs

      A DESCRIPTION OF THE REQUEST :
      It would be nice to add intermediate operations that correspond to each terminal operation in the Stream API. Rather than terminating, these methods would add an additional parameter - a Consumer - and return back a Stream. When the Stream does terminate, it computes any of these intermediate operations along with the terminal operation, and the results of the intermediate operations are sent to the supplied Consumers.

      JUSTIFICATION :
      I often find myself wanting to get the results of multiple terminal operations from a Stream. I either create the Stream twice and compute the different operations on different Streams, or I create complicated/unreadable reduce functions. It would be nice to chain terminal operations where the results are sent to a Consumer so I can get the results of multiple terminal operations with just one Stream.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      A few examples of an intermediate operation corresponding to a terminal operation would be:
      public Stream<T> count(LongConsumer result);
      public Stream<T> reduce(T identity, BinaryOperator<T> accumulator, Consumer<? super T> result);

      The following is an example for calculating the standard deviation by chaining the proposed intermediate operations.

      double sum = 0, squareSum = 0;
      long count = 0;
      public void example(DoubleStream stream) {
      stream.sum(val -> sum = val)
      .reduce(0, val -> val * val, val -> squareSum = val)
      .count(val -> count = val)
      .close();
      double stdDevation = (squareSum - sum * sum) / count;
      }

            psandoz Paul Sandoz
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: