如何将 Java 流转换为滑动窗口?
将流转换为滑动窗口的推荐方法是什么?
What is the recommended way to transform a stream into a sliding window?
例如,在 Ruby 中,您可以使用 each_cons:
For instance, in Ruby you could use each_cons:
irb(main):020:0> [1,2,3,4].each_cons(2) { |x| puts x.inspect }
[1, 2]
[2, 3]
[3, 4]
=> nil
irb(main):021:0> [1,2,3,4].each_cons(3) { |x| puts x.inspect }
[1, 2, 3]
[2, 3, 4]
=> nil
在 Guava 中,我发现只有 Iterators#partition,相关但没有滑动窗口:
In Guava, I found only Iterators#partition, which is related but no sliding window:
final Iterator<List<Integer>> partition =
Iterators.partition(IntStream.range(1, 5).iterator(), 3);
partition.forEachRemaining(System.out::println);
-->
[1, 2, 3]
[4]
推荐答案
API中没有这个函数,因为它同时支持顺序和并行处理,对于任意流源的滑动窗口函数很难提供高效的并行处理(即使是高效的对并行处理也相当困难,我实现了它,所以我知道).
There's no such function in the API as it supports both sequential and parallel processing and it's really hard to provide an efficient parallel processing for sliding window function for arbitrary stream source (even efficient pairs parallel processing is quite hard, I implemented it, so I know).
但是,如果您的源是具有快速随机访问的 List
,您可以使用 subList()
方法来获得所需的行为,如下所示:
However if your source is the List
with fast random access, you can use subList()
method to get the desired behavior like this:
public static <T> Stream<List<T>> sliding(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));
}
我的 StreamEx 库中实际上提供了类似的方法:请参阅 StreamEx.ofSubLists()
.
Similar method is actually available in my StreamEx library: see StreamEx.ofSubLists()
.
还有一些其他第三方解决方案不关心并行处理并使用一些内部缓冲区提供滑动功能.例如,质子包 StreamUtils.windowed
.
There are also some other third-party solutions which don't care about parallel processing and provide sliding functionality using some internal buffer. For example, protonpack StreamUtils.windowed
.
相关文章