我终于找到了一个解决方案,尽管它不是面向缓冲区的。灵感是首先解决滑动窗口为 2 的问题:
Flux<Integer> primary = Flux.fromStream(IntStream.range(0, 10).boxed());
primary.flatMap(num -> Flux.just(num, num))
.skip(1)
.buffer(2)
.filter(list -> list.size() == 2)
.map(list -> Arrays.toString(list.toArray()))
.subscribe(System.out::println);
该过程的可视化表示如下:
1 2 3 4 5 6 7 8 9
V V V V V V V V V Flux.just(num, num)
1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
V V V V V V V V V skip(1)
1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
V V V V V V V V V bufffer(2)
1 2, 2 3, 3 4, 4 5, 5 6, 6 7, 7 8, 8 9, 9
V V V V V V V V V filter
1 2, 2 3, 3 4, 4 5, 5 6, 6 7, 7 8, 8 9
这是输出:
[0, 1]
[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
[6, 7]
[7, 8]
[8, 9]
然后我将上面的想法概括为一个任意滑动窗口大小的解决方案:
public class SlidingWindow {
public static void main(String[] args) {
System.out.println("Different sliding windows for sequence 0 to 9:");
SlidingWindow flux = new SlidingWindow();
for (int windowSize = 1; windowSize < 5; windowSize++) {
flux.slidingWindow(windowSize, IntStream.range(0, 10).boxed())
.map(SlidingWindow::listToString)
.subscribe(System.out::print);
System.out.println();
}
//show stream difference: x(i)-x(i-1)
List<Integer> sequence = Arrays.asList(new Integer[]{10, 12, 11, 9, 13, 17, 21});
System.out.println("Show difference 'x(i)-x(i-1)' for " + listToString(sequence));
flux.slidingWindow(2, sequence.stream())
.doOnNext(SlidingWindow::printlist)
.map(list -> list.get(1) - list.get(0))
.subscribe(System.out::println);
System.out.println();
}
public <T> Flux<List<T>> slidingWindow(int windowSize, Stream<T> stream) {
if (windowSize > 0) {
Flux<List<T>> flux = Flux.fromStream(stream).map(ele -> Arrays.asList(ele));
for (int i = 1; i < windowSize; i++) {
flux = addDepth(flux);
}
return flux;
} else {
return Flux.empty();
}
}
protected <T> Flux<List<T>> addDepth(Flux<List<T>> flux) {
return flux.flatMap(list -> Flux.just(list, list))
.skip(1)
.buffer(2)
.filter(list -> list.size() == 2)
.map(list -> flatten(list));
}
protected <T> List<T> flatten(List<List<T>> list) {
LinkedList<T> newl = new LinkedList<>(list.get(1));
newl.addFirst(list.get(0).get(0));
return newl;
}
static String listToString(List list) {
return list.stream()
.map(i -> i.toString())
.collect(Collectors.joining(", ", "[ ", " ], "))
.toString();
}
static void printlist(List list) {
System.out.print(listToString(list));
}
}
上述代码的输出如下:
Different sliding windows for sequence 0 to 9:
[ 0 ], [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ], [ 7 ], [ 8 ], [ 9 ],
[ 0, 1 ], [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ], [ 5, 6 ], [ 6, 7 ], [ 7, 8 ], [ 8, 9 ],
[ 0, 1, 2 ], [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4, 5 ], [ 4, 5, 6 ], [ 5, 6, 7 ], [ 6, 7, 8 ], [ 7, 8, 9 ],
[ 0, 1, 2, 3 ], [ 1, 2, 3, 4 ], [ 2, 3, 4, 5 ], [ 3, 4, 5, 6 ], [ 4, 5, 6, 7 ], [ 5, 6, 7, 8 ], [ 6, 7, 8, 9 ],
Show difference 'x(i)-x(i-1)' for [ 10, 12, 11, 9, 13, 17, 21 ],
[ 10, 12 ], 2
[ 12, 11 ], -1
[ 11, 9 ], -2
[ 9, 13 ], 4
[ 13, 17 ], 4
[ 17, 21 ], 4