1

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.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
blue-sky
  • 51,962
  • 152
  • 427
  • 752

1 Answers1

1

I think this is what you want:

public static <T> Stream<List<T>> createSlidingWindow(List<T> list, int size) {
    return IntStream.range(0, list.size())
            .mapToObj(i -> list.subList(
                    Math.min(list.size(), size * i),
                    Math.min(list.size(), size + (size * i))))
            .filter(l -> !l.isEmpty());
}

IntStream#range(int, int) assures an ordered sequence of numbers from the left int to the right one (exclusive) for iterating the index. The subsequent mapToObj uses List#subList(int, int) to define chunks or partitions from the original list depending on the current pivot (i) position in the "loop". Here is the output:

[1, 2, 3]
[4, 5]

My algorithm is not the most effective/neat since you need to filter out the empty chunks using .filter(l -> !l.isEmpty()) however, you have the idea and let the little modification be up to you.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183