我正在尝试对组中的顶级对象进行分组、排序和挑选,该组还将包含来自该组的所有对象的一个字段的字段值列表。例如给出记录
客户ID | 时间 | 产品 |
---|---|---|
1 | 06:00:00 | 100 |
1 | 06:05:00 | 101 |
1 | 06:10:00 | 102 |
2 | 06:00:00 | 101 |
2 | 06:10:00 | 103 |
3 | 06:15:00 | 102 |
3 | 06:10:00 | 103 |
结果
客户ID | 时间 | 产品 |
---|---|---|
1 | 06:10:00 | 100#101#102 |
2 | 06:10:00 | 101#103 |
3 | 06:15:00 | 102#103 |
Product
字段是 String
类型,因此希望我可以连接字符串以形成所需的格式。产品顺序并不重要。
我有两个代码块。首先进行分组、排序并选择第一个。其次生成产品列表。但是我无法将
Product
列与列表合并和更新。
第一部分
Map<String, CustEvent> map = custEventList.stream().collect(
Collectors.groupingBy(
CustEvent::getCustId,
Collectors.collectingAndThen(
Collectors.toList(),
values -> values.stream()
.sorted(Comparator.comparing(CustEvent::getTime, Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
.collect(toList()).get(0)
)));
第二部分
Map<String, String> custProducts = custEventList.stream()
.collect(groupingBy(CustEvent::getCustId,
mapping(CustEvent::getProduct, joining("#"))));
有什么建议吗?
您可以在找到
maxTimeEvent
(CustEvent
每组的最大时间)后立即添加产品列表生成代码。之后,您可以通过流过 products
,将每个 values
映射到其 CustEvent
字段,然后使用 Product
收集器连接它们来创建一个字符串(例如 Collectors.joining("#")
)。最后,将字符串设置为 Product
的 maxTimeEvent
字段,并返回 maxTimeEvent
作为结果。比如:
Map<String, CustEvent> map = custEventList.stream().collect(
Collectors.groupingBy(
CustEvent::getCustId,
Collectors.collectingAndThen(
Collectors.toList(),
values -> {
CustEvent maxTimeEvent = values.stream()
.sorted(Comparator.comparing(CustEvent::getTime, Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
.collect(Collectors.toList()).get(0);
String products = values.stream()
.map(CustEvent::getProduct)
.collect(Collectors.joining("#"));
maxTimeEvent.setProduct(products);
return maxTimeEvent;
}
)));