limit and skip in StreamOps
Brian Goetz
brian.goetz at oracle.com
Sat Aug 4 08:03:53 PDT 2012
Yep, already on the "to consider" list.
On Aug 4, 2012, at 6:51 AM, Deepak S Patwardhan wrote:
> Hello,
>
> Consider the following class which represents an infinite stream of natural
> numbers.
>
> public class Naturals implements Streamable<Integer> {
>
> private int current = 1;
>
> public Iterator<Integer> iterator() {
> return new Iterator<Integer>() {
> //.. hasNext() returns true
> //.. remove is unsupported
>
> @Override public Integer next() {
> return current ++;
> }
> };
> }
> }
>
> To compute the sum of first 5 numbers, I have to write
>
> Stream<Integer> sumStream = naturals.cumulate((x, y) -> x + y);
> for (int i = 0; i < 4; i++) sumStream.next();
> int sum5 = sumStream.next();
>
> Question 1) How about a (lazy) limit method in StreamOps which results in a
> sized stream? I can then write
> int sum5 = naturals.limit(5).reduce(0, (x, y) -> x + y);
>
> Question 2) How about a (an eager) skip method in StreamOps which skips
> elements in the stream? I can then write
> int sum5 = naturals.cumulate((x, y) -> x + y).skip(4).next();
>
> Although I have raised these in the context of infinite streams, I think
> they would apply to sized streams as well.
>
> Regards,
> Deepak S Patwardhan.
>
>
>
More information about the lambda-dev
mailing list