Stream.limit() - puzzler/bug/feature

Brian Goetz brian.goetz at oracle.com
Thu Nov 15 09:22:14 PST 2012


The best way to think about it is that a Stream is more like an Iterator 
than a data structure.  There is some abstract source of data somewhere 
(it might be in a data structure, or might be generated from a function, 
or read from a network), and a series of transformations applied to the 
data between the source and the consumer.  Streams can additionally 
execute using parallelism, if requested.

Stream constructs like:

Stream<Person> s = people.stream()
                          .filter(p -> p.getLastName().equals("Smith")))

do not do any filtering on construction.  It simply says "there's a 
stream source, the collection 'people', and when you consume from the 
stream s, you'll get the results of filtering the source values."

The confusion in Dmitry's example is akin to multiple activities reading 
from the same IO channel -- they might interfere with each other over 
who gets the next value, and any buffering that any consumer does may 
confuse other consumers.



On 11/15/2012 12:11 PM, Marcus Thiesen wrote:
> Hey List,
>
> sorry, I haven't followed the whole Stream discussion and without publicliy
> available JavaDocs (are there?) I'm currently trying to figure out what
> this comment means, because without all that background I read the code as
> annotated:
>
> 2012/11/15 Dmitry Bessonov <dmitry.bessonov at oracle.com>
>
>> While playing with method Sream.limit(int) using a mini-code like
>>
>>           final Stream<Integer> s = Arrays.asStream(1, 2, 3, 4, 5);
>>
>
> Give me a "Stream" view of the Array int[] 1, 2, 3, 4, 5.
>
>
>
>>           final Stream<Integer> to3 = s.limit(3);
>>
>
> Give me a Stream view of s limitted to 3 values.
>
>
>>           final Stream<Integer> to4 = s.limit(4);
>>
>
> Give me a Stream view of s limitted to 4 values.
>
>
>>
>> have to admit that there's no unambiguous answer
>> to the question of contents  of streams "to3" and "to4".
>> It depends on which of the streams is consumed first.
>>
>>
> My best guess would be to3 = [ 1, 2, 3 ] and to4 = [ 1, 2, 3, 4 ].
>
> Given my naive understanding of the above code the comment does not make
> sense. The only way the above comment makes sense is that we are not
> talking of (somehow immutable) views here but that those operations mutate
>   the backing array on read time of the resulting stream. Am I right?
>
> Cheers,
>    Marcus
>
>
>
>


More information about the lambda-dev mailing list