How to transform a Java stream into a sliding window?(如何将 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
.
这篇关于如何将 Java 流转换为滑动窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 Java 流转换为滑动窗口?
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01