【发布时间】:2019-03-05 07:39:35
【问题描述】:
我有这个对象列表
List<DetailDto> details;
@Value
public class DetailDto implements Serializable {
String category1;
Integer category2;
Integer price;
transient Integer totalPrice;
}
这个列表
[
{
"category1": "ABC",
"category2": 30,
"price": 195,
"totalPrice": null
},
{
"category1": "ABC",
"category2": 30,
"price": 195,
"totalPrice": null
},
{
"category1": "ABC",
"category2": 30,
"price": 195,
"totalPrice": null
},
{
"category1": "ABC",
"category2": 30,
"price": 390,
"totalPrice": null
},
{
"category1": "ABC",
"category2": 30,
"price": 390,
"totalPrice": null
},
{
"category1": "DEF",
"category2": 30,
"price": 455,
"totalPrice": null
},
{
"category1": "DEF",
"category2": 30,
"price": 455,
"totalPrice": null
},
{
"category1": "DEF",
"category2": 30,
"price": 455,
"totalPrice": null
},
{
"category1": "DEF",
"category2": 30,
"price": 455,
"totalPrice": null
},
{
"category1": "GHI",
"category2": 1,
"price": 18000,
"totalPrice": null
}
]
我想通过将price 字段与条件为的totalPrice 字段相加来创建另一个List<DetailDto> 对象:
- 字符串
category1很常见 - 整数
category2很常见 - 整数
price很常见
在这一点上我有这个
List<List<DetailDto>> summarizedList = detail().stream()
.collect(Collectors.groupingBy(DetailDto::category1,
Collectors.groupingBy(DetailDto::category2,
Collectors.groupingBy(DetailDto::price))))
.values()
.stream()
.flatMap(c1 -> c1.values().stream())
.flatMap(c2 -> c2.values().stream())
.collect(Collectors.toList());
返回给我List<List<DetailDto>>
我不知道怎么弄好,我试了之后
summarizedList.stream().map(dto -> dto.stream().reduce((x,y) -> new DetailDto(x.productCode(), x.productQt(), x.orderPrice(), Integer.sum(x.orderPrice(), y.orderPrice()).orElse(null).collect(Collectors.toList());
它会返回
[
{
"category1": "ABC",
"category2": 30,
"price": 195,
"totalPrice": 390
},
{
"category1": "ABC",
"category2": 30,
"price": 390,
"totalPrice": 780
},
{
"category1": "DEF",
"category2": 30,
"price": 455,
"totalPrice": 910
},
{
"category1": "GHI",
"category2": 1,
"price": 18000,
"totalPrice": null
}
]
我真正需要的是
[
{
"category1": "ABC",
"category2": 30,
"price": 195,
"totalPrice": 585
},
{
"category1": "ABC",
"category2": 30,
"price": 390,
"totalPrice": 780
},
{
"category1": "DEF",
"category2": 30,
"price": 455,
"totalPrice": 1820
},
{
"category1": "GHI",
"category2": 1,
"price": 18000,
"totalPrice": 18000
}
]
你们能帮帮我吗?
【问题讨论】:
-
基于
category1、category2和price为POJO 实现equals,并使用更新totalPrice的合并函数收集toMap。