I want to group different objects types based on same content of fields incomeCode, endDate and codeRef on both classes. I omitted many fields on both classes that make each object unique for simplicity.
public class Exon {
private Long id;
private IncomeCode incomeCode;
private LocalDate endDate;
String codeRef;
}
public class Sup {
private Long id;
private IncomeCode incomeCode;
private LocalDate startDate;
private LocalDate endDate;
String codeRef;
}
Exons example:
| id | incomdeCode | endDate | codeRef |
|---|---|---|---|
| 1 | 45 | 01/01/2021 | 4 |
| 2 | 21 | 01/01/2022 | 5 |
| 3 | 33 | 01/01/2023 | 2 |
| 4 | 45 | 01/01/2021 | 4 |
Sups example:
| id | incomdeCode | endDate | codeRef |
|---|---|---|---|
| 1 | 45 | 01/01/2021 | 4 |
| 2 | 21 | 01/01/2022 | 5 |
| 3 | 33 | 01/01/2023 | 2 |
Desired result : List : { {exon1, exon4, sup1}, {exon2, sup2}, {exon3, sup3} }
My attempt :
public Map<Object, List<Exon>> getExons() {
Map<Object, List<Exon>> result = getSource1.stream()
.flatMap(lp -> lp.getExons().stream())
.collect(Collectors.groupingBy(e -> new KeyGroup(e.getIncomeCode(), e.getEndDate(), e.getCodeRef())
));
return result;
}
public Map<Object, List<Sup>> getSups() {
Map<Object, List<Sup>> result = getSource2.stream()
.flatMap(lp -> lp.getSups().stream())
.collect(Collectors.groupingBy(e -> new
KeyGroup(e.getIncomeCode(), e.getEndDate(), e.getCodeRef())));
return result;
}
Map<Object, List<Exon>> exonList = getExons();
Map<Object, List<Sup>> supList = getSups();
Map<Object, List<List<?>>> objMap = new HashMap<>();
exonList.forEach((k, v) -> {
if (objMap.containsKey(o)) {
objMap.get(o).add(v);
} else {
List<List<?>> eList = new ArrayList<>();
eList.add(v);
objMap.put(o, eList);
}
});
supList.forEach((o, v) -> {
if (objMap.containsKey(o)) {
objMap.get(o).add(v);
} else {
List<List<?>> eList = new ArrayList<>();
eList.add(v);
objMap.put(o, eList);
}
});
exonandsuphave no common super type apart fromObject. BTW, class names by convention should start in with upper-case letter.Objectas generic type is as bad as not use generics at all.