We have two lists in Java, as shown below. And I need to get all elements from these two lists and if there is same id with the same date we need to sum the cost` of such elements in these lists.
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 |
The results should be
results list should be - >
| 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 this is based on date condition and id)
What I have tried till now is this
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());
I am able to get all the data but after this step I need to get all the data and if there is same date and same id we need to sum up the cost from listA with the cost of listB