-
Enhancement
-
Resolution: Duplicate
-
P4
-
None
-
12
-
None
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.
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.
- duplicates
-
JDK-8140283 add Stream::transform method to facilitate fluent chaining of other methods
- Open
- relates to
-
JDK-8201273 add operation to extract the only element from a stream
- Open
-
JDK-8180352 Add Stream.toList() method
- Resolved
-
JDK-8157790 java.util streams "filterNot(predicate)" for collections
- Closed
-
JDK-8198620 New Convenient-Methods for java.util.stream.Stream
- Closed