limit and skip in StreamOps
Deepak S Patwardhan
deepak.patwardhan at itaas.com
Sat Aug 4 06:51:17 PDT 2012
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