On Tue, 3 Nov 2020 11:05:21 GMT, Stephen Colebourne <scolebou...@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 1168: > >> 1166: * Accumulates the elements of this stream into a {@code List}. >> The elements in >> 1167: * the list will be in this stream's encounter order, if one >> exists. There are no >> 1168: * guarantees on the implementation type, mutability, >> serializability, or > > It would be useful for callers to feel more confident that they will get an > immutable instance. In java.time.* we have wording like "This interface > places no restrictions on the mutability of implementations, however > immutability is strongly recommended." Could something like that work here, > emphasising that everyone implementing this method should seek to return an > immutable list? Yes, good point, the "no guarantee of mutability" clashes with the later statement about the possibility of the returned instance being value-based, which strongly implies immutability. I'll work on tuning this up to be a stronger statement on immutability, while retaining "no-guarantee" for implementation type, serializability, etc. I think we do want to preserve future implementation flexibility in those areas. ------------- PR: https://git.openjdk.java.net/jdk/pull/1026