java 二元组,使用RXJava 2对数据分组,将元素添加到每个组并输出一个列表

本文介绍了如何使用RXJava2处理包含日期对象的数据流,具体包括按月份和年份分组,添加头部元素,排序以及将所有元素合并回单一列表的操作。通过使用groupBy、flatMap、sorted等操作符,实现了复杂的数据处理流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have an RXJava 2 observer that emits objects of type somethingWithDate. These objects have a property that contains a java date object as well as a boolean isHeader.

What I need to do with these objects is:

Group them by month and year (all dates in January of 2017, all dates in January of 2016, all dates in February 2016, ...)

Add a header (also a somethingWithDate) at the start of the group

Sort groups in regard to each other (by date, sorting inside the groups would be nice too but not needed, the header needs to stay at first position in each group)

Merged(?) all elements from all groups back into one list of elements single>

Here is an example (all objects of type somethingWithDate, but I will only display the important properties here to make it more readable):

Input Data:

1.1.2017, 2.1.2017, 1.1.2016, 8.8.2017

Result:

header, 1.1.2016, header, 1.1.2017, 2.1.2017, header, 8.8.2017

I know 1. can be achieved by using groupBy(). I haven't found a way to do 2 though. I also know there is a toList() and toSortedList() to maybe use for 3. and 4. but I am unsure how that works with the groups from the groupBy() and how I can collect them back in one list.

Pseudocode:

inputListObserver

.groupBy(obj.date.year + obj.date.month)

.map(group -> group.addAtBeginning(headerElement))

.sortBy(groupKey)

.mergeToList()

...

解决方案

I think I finally found an answer. Using flatmap (thanks for the idea @masps)seems to do the trick. Here is the pseudo code:

.groupBy(makeKeyFromMonthAndYear()) // groups everything in months

.sorted(byGroupKey) // sorts the groups

.flatMap( // collect all groups back into one

.startsWith(generateHeaderElement()) // add a header for each group

.sorted() // optional, sort the values in a month

)

.toList() // output a Single>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值