On Wed, 4 Nov 2020 08:50:49 GMT, Zheka Kozlov 
<github.com+761899+orio...@openjdk.org> wrote:

>> This change introduces a new terminal operation on Stream. This looks like a 
>> convenience method for Stream.collect(Collectors.toList()) or 
>> Stream.collect(Collectors.toUnmodifiableList()), but it's not. Having this 
>> method directly on Stream enables it to do what can't easily by done by a 
>> Collector. In particular, it allows the stream to deposit results directly 
>> into a destination array (even in parallel) and have this array be wrapped 
>> in an unmodifiable List without copying.
>> 
>> In the past we've kept most things from the Collections Framework as 
>> implementations of Collector, not directly on Stream, whereas only 
>> fundamental things (like toArray) appear directly on Stream. This is true of 
>> most Collections, but it does seem that List is special. It can be a thin 
>> wrapper around an array; it can handle generics better than arrays; and 
>> unlike an array, it can be made unmodifiable (shallowly immutable); and it 
>> can be value-based. See John Rose's comments in the bug report:
>> 
>> https://bugs.openjdk.java.net/browse/JDK-8180352?focusedCommentId=14133065&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-14133065
>> 
>> This operation is null-tolerant, which matches the rest of Streams. This 
>> isn't specified, though; a general statement about null handling in Streams 
>> is probably warranted at some point.
>> 
>> Finally, this method is indeed quite convenient (if the caller can deal with 
>> what this operation returns), as collecting into a List is the most common 
>> stream terminal operation.
>
> src/java.base/share/classes/java/util/stream/Stream.java line 1192:
> 
>> 1190:     @SuppressWarnings("unchecked")
>> 1191:     default List<T> toList() {
>> 1192:         return (List<T>) Collections.unmodifiableList(new 
>> ArrayList<>(Arrays.asList(this.toArray())));
> 
> Why can't we return `listFromTrustedArrayNullsAllowed` here as in 
> `ReferencePipeline`?
> Or at least, we should avoid unnecessary copying of arrays. See [how this is 
> done](https://github.com/amaembo/streamex/blob/master/src/main/java/one/util/streamex/AbstractStreamEx.java#L1313)
>  in StreamEx.

`listFromTrustedArrayNullsAllowed` is clearly not an option, as it will produce 
shared-secret leaking (see 
[JDK-8254090](https://bugs.openjdk.java.net/browse/JDK-8254090) for a similar 
case). StreamEx solution is dirty as it relies on the implementation detail. I 
believe, OpenJDK team is not very interested in providing optimal 
implementations for third-party stream implementations, as third-party 
implementations will likely update by themselves when necessary. At least, my 
suggestion to make the default `mapMulti` implementation better was declined.

-------------

PR: https://git.openjdk.java.net/jdk/pull/1026

Reply via email to