Idiomatic Windowing on Streams
Richard Warburton
richard.warburton at gmail.com
Fri Oct 25 15:49:03 PDT 2013
Hi,
Sometimes its useful to be able to operate on a time-window over a stream
of data with a defined encounter order. So for an element at index i, I
want to perform an operation on a stream of that element and the next n
elements. The most trivial example I can think of is a simple moving
average of data points.
I'm currently struggling to find a way to idiomatically express this in the
Streams framework. My current best effort is to take a stream of indices
and map those indices to a substream of my original stream of data and I
can then do some reduction over those elements. So here's an SMA for
example:
double[] means =
IntStream.range(0, numbers.size() - N)
.mapToDouble(i ->
numbers.stream()
.substream(i, i + N)
.mapToInt(x -> x)
.average()
.getAsDouble())
.toArray();
Is there a better approach than this?
regards,
Dr. Richard Warburton
http://insightfullogic.com
@RichardWarburto <http://twitter.com/richardwarburto>
More information about the lambda-dev
mailing list