如何将Java流转换为滑动窗口? [英] How to transform a Java stream into a sliding window?

查看:611
本文介绍了如何将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流转换为滑动窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆