Implementing a sliding window I've written this :
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class PreProcess {
public static <T> Stream<List<T>> createSlidingWindow(List<T> list, int size) {
if(size > list.size())
return Stream.empty();
return IntStream.range(0, list.size()-size+1)
.mapToObj(start -> list.subList(start, start+size));
}
public static void main(String args[]) throws ParseException {
Stream<List<Integer>> sw = createSlidingWindow(Arrays.asList(1, 2, 3, 4 ,5) , 3);
sw.forEach(x -> {
System.out.println(x);
});
}
}
Executing this code prints:
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
I'm attempting to modify so that there is no overlap between each window so a sliding window of size 3 will return:
[1, 2, 3]
[4, 5]
I think I need to modify start
so that it's pointing to the next window but I'm unsure how to do achieve this using streams.