Java中有两个列表,如下所示.我需要从这两个列表中获取所有元素,如果这些列表中有相同的id
个元素,这些元素的成本相同.
List<A> listA = new ArrayList<>();
List<A> listB = new ArrayList<>();
List<A> results = new ArrayList<>();
listA
:
Id | Date | Cost |
---|---|---|
1 | 2022-01-01 | 11.65 |
2 | 2022-02-01 | 12.65 |
2 | 2022-03-01 | 13.65 |
3 | 2022-05-01 | 19.5 |
listB
:
Id | Date | Cost |
---|---|---|
1 | 2022-04-01 | 1.65 |
1 | 2022-05-01 | 134.65 |
2 | 2022-02-01 | 12.65 |
2 | 2022-09-01 | 7.8 |
3 | 2022-06-01 | 3.65 |
结果应该是
结果列表应为->;
Id | Date | Cost |
---|---|---|
1 | 2022-01-01 | 11.65 |
1 | 2022-04-01 | 1.65 |
1 | 2022-05-01 | 134.65 |
2 | 2022-02-01 | 25.3* |
2 | 2022-03-01 | 13.65 |
2 | 2022-09-01 | 7.8 |
3 | 2022-05-01 | 19.5 |
3 | 2022-06-01 | 3.65 |
*(listA.cost+listB.cost这基于日期条件和id)
到目前为止,我一直在try 的是
Stream.concat(
listA.stream().map(d -> new Result(d.getId(), d.getDate()), d.getCost()),
listB.stream().map(b -> new Result(b.getId(), b.getDate(), b.getCost())
)
.collect(Collectors.toList());
我能够获得所有数据,但在这一步之后,我需要获得所有数据,如果有相同的date
和相同的id
,我们需要将listA
中的cost
相加,成本为listB