No-reuse streams

Remi Forax forax at univ-mlv.fr
Mon Nov 19 14:52:42 PST 2012


On 11/19/2012 05:19 PM, Aleksey Shipilev wrote:
> Well, of course!
>
> I was thinking about returning the same iterator nevertheless; so that
> we share the traversal states between two iterators from iterator()
> call. I think this provisioning would help to write cleaner code in some
> of the cases, at the cost of making stream appear to bear the state. I'm
> fine with opting out of that behavior if it is considered not that clean.

Stream is a weaker version of an Iterator, weaker because even
if the terminal op doesn't consume the whole stream, you can't access
to the data that were not consumed.

The method iterator() is not a method that should be used in most
of the use cases when you use a Stream, The method is here
just for interropt between the new world of streams and the old world of 
iterators.

The method iterator() allows you to upgrade a stream to the stronger 
semantics
of the Iterator but in that case you can't use the fancy method of 
stream anymore.
This allow us to have a clean specification of the state of a stream 
after terminal op like findFirst(),
you can't access the non-consumed data.

Given this is an interropt feature, The Stream implementations should 
not have to
have an additional field for implementing the semantics you propose
but you can store the iterator in a local variable in the code that use 
stream.iterator()
if you want to re-use the iterator.

>
> -Aleksey.

Rémi

>
> On 11/19/2012 07:50 PM, Brian Goetz wrote:
>> The iterator() method (and soon, spliterator()) are the escape hatch for
>> "the library can't help me, I have to do it myself."  You then get the
>> iterator and can do whatever you want with it.  But, what you can't do
>> is call iterator(), pull elements from the stream, and *then* try and do
>> more stream operations on that stream.
>>
>> On 11/19/2012 10:01 AM, Aleksey Shipilev wrote:
>>> On 11/19/2012 06:29 PM, Paul Sandoz wrote:
>>>> Brian and I just pushed a changeset that:
>>>>
>>>> - turns Stream/IntStream.iterator() into a terminal operation
>>>>
>>>> - only one terminal operation may be performed on at most one stream
>>>> in the pipeline, otherwise an ISE will be thrown.
>>> Isn't iterator() the exception from this rule, being the "extension" of
>>> the stream? I would naturally presume the *same* iterator is returned
>>> for the given stream, so this will still be the valid code:
>>>
>>>    Stream<T> stream = ...;
>>>    T first = stream.iterator().next()
>>>    // ...many, many lines of code...
>>>    T second = stream.iterator().next()
>>>
>>> -Aleksey.
>>>
>



More information about the lambda-dev mailing list