JDK-8210372 : Streams should allow chaining with custom stream implementations
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util.stream
  • Affected Version: 12
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • Submitted: 2018-09-04
  • Updated: 2018-10-29
  • Resolved: 2018-09-04
Related Reports
Duplicate :  
Relates :  
Relates :  
Relates :  
Relates :  
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.

Comments
Oops. Such request has already been filed: JDK-8140283 And with exactly the same name of new method: Stream.chain() Closing this as a duplicate.
29-10-2018