Model:
Year{
int year;
}
ObjectB{
ObjectBA bb; <- ObjectBA{int value}
ObjectBB ba; <- ObjectBA{int value}
}
ObjectC{
List<ObjectBA>
List<ObjectBB>
}
How to convert:
Map<Year, List<ObjectB>>
to
Map<Year, ObjectC>
where Object C have all element from ObjectB
I already have:
var result = inputMap.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> e.getValue().stream().
map(
value -> value.bb().getValue()
).toList())
);
i need something that give me multimple list in Object, like:
map(
new ObjectC(
value -> value.ba().getValue(),
value -> value.bb().getValue()
).toList())
CodePudding user response:
What you've got looks pretty good already. Just replace the value mapper with e -> convert(e.getValue())
where convert
is like the function below that converts a List<ObjectB>
into an ObjectC
:
ObjectC convert(List<ObjectB> list) {
ObjectC c = new ObjectC();
for (ObjectB b : list) {
c.ba.add(b.ba);
c.bb.add(b.bb);
}
return c;
}
Or if you'd prefer to stick with just using streams, try Stream#collect
like so:
e.getValue().stream().collect(
() -> new ObjectC(),
(c, b) -> {
c.ba.add(b.ba);
c.bb.add(b.bb);
},
(c1, c2) -> {
c1.ba.addAll(c2.ba);
c1.bb.addAll(c2.bb);
}
)