I have a double[] with K*N elements. I would like to split this into a stream (list/array/...) of N long[] arrays of size K. I already found a solution, but it looks quite dirty and requires a stateful Mapper (I think they are meant to be stateless):
private class DataToLong implements DoubleFunction<long[]> {
int d = 0;
long[] buf = new long[K];
@Override
public long[] apply(double value) {
buf[d] = BitTools.toSortableLong(value);
d++;
long[] ret = null;
if (d >= K) {
ret = buf;
buf = new long[K];
d = 0;
}
return ret;
}
}
public void load(double[] data, int K) {
Arrays.stream(data).mapToObj(new DataToLong())
.filter((x)-> x != null).forEach((buf)->{
//here we do something with 'buf'
});
}
The above code seems to work, but it's actually longer than the non-streams version of the code and it violates the stateless requirements of the Mapper. It there any better way to achieve the same thing?