Java 8复杂的自定义收集器 [英] Java 8 complex custom collector

查看:270
本文介绍了Java 8复杂的自定义收集器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象流,我想按以下方式收集。

I have a stream of objects which I would like to collect the following way.

假设我们正在处理论坛帖子:

Let's say we are handling forum posts:

class Post {
    private Date time;
    private Data data
}

我想创建一个列出帖子的列表一段时间。如果X分钟没有帖子,请创建新组。

I want to create a list which groups posts by a period. If there were no posts for X minutes, create new group.

class PostsGroup{
    List<Post> posts = new ArrayList<> ();
}

我想获得列表< PostGroups> 包含按时间间隔分组的帖子。

I want to get a List<PostGroups> containing the posts grouped by the interval.

示例:间隔10分钟。

帖子:

[{time:x, data:{}}, {time:x + 3, data:{}} , {time:x+ 12, data:{}, {time:x + 45, data:{}}}]

我想获得一个帖子组列表:

I want to get a list of posts group:

[
 {posts : [{time:x, data:{}}, {time:x + 3, data:{}}, {time:x+ 12, data:{}]]},
{posts : [{time:x+ 45, data:{}]}
]




  • 注意到第一组持续到X + 22.然后在X + 45收到一个新帖子。

  • 这可能吗?

    推荐答案

    使用 groupRuns StreamEx 库的方法:

    long MAX_INTERVAL = TimeUnit.MINUTES.toMillis(10);
    StreamEx.of(posts)
            .groupRuns((p1, p2) -> p2.time.getTime() - p1.time.getTime() <= MAX_INTERVAL)
            .map(PostsGroup::new)
            .toList();
    

    我假设你有一个构造函数

    I assume that you have a constructor

    class PostsGroup {
        private List<Post> posts;
    
        public PostsGroup(List<Post> posts) {
            this.posts = posts;
        }
    }
    

    StreamEx.groupRuns 方法采用 BiPredicate ,它应用于两个相邻的输入元素,如果必须组合在一起,则返回true。此方法创建列表流,其中每个列表代表该组。这种方法很懒惰,可以在并行流中正常工作。

    The StreamEx.groupRuns method takes a BiPredicate which is applied to two adjacent input elements and returns true if they must be grouped together. This method creates the stream of lists where each list represents the group. This method is lazy and works fine with parallel streams.

    这篇关于Java 8复杂的自定义收集器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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