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

Streams should allow chaining with custom stream implementations

    XMLWordPrintable

    Details

    • Type: Enhancement
    • Status: Closed
    • Priority: P4
    • Resolution: Duplicate
    • Affects Version/s: 12
    • Fix Version/s: None
    • Component/s: core-libs
    • Labels:
      None

      Description

      From time to time we receive requests to add new methods to j.u.s.Stream.
      However it's not always desirable to extend the existing API, as the proposed additions are not necessarily mean to be used widely.

      One of the reasons why users request such extensions is that there isn't a way to *both* create a custom Stream class *and* use standard library's stream producers (e.g. List.stream()).

      One approach to the issue is to allow chaining a Stream with an object of arbitrary type: If we provide a BaseStream method
          @SuppressWarnings("unchecked")
          default <R> R chain(Function<? super S, R> chaineeMaker) {
              return chaineeMaker.apply((S)this);
          }

      then a Stream type can be changed on the fly like:
              long z = List.of(1, 2, 3, 4)
                  .stream()
                  .filter(x -> x > 1)
                  .chain(MyStream::new)
                  .myCount();

      Where MyStream is a custom stream implementation (which doesn't even have to extend j.u.s.Stream):
          class MyStream {
              private Stream<?> s;
              public MyStream(Stream<?> s) {
                  this.s = s;
              }
              public long myCount() {
                  return s.count() * 11011011;
              }
          }

      Alternatively, we can introduce an interface Chainable with the default method chain() as above, and make BaseStream implement it.
      In this case, other classes, which utilize chaining syntax may also implement Chainable and thus will allow chaining to custom extensions.

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                igerasim Ivan Gerasimov
                Reporter:
                igerasim Ivan Gerasimov
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: