I have classes Similar to:
class Response {
Source source;
Target target;
}
class Source {
Long sourceId;
String sourceName;
}
class Target {
Long targetId;
String targetName;
}
In the Response, source(sourceId,sourceName) could be the same for different target object.
I have entry in Response with these 4 properties sourceId, sourceName, targetId, targetName. I can have sourceId, sourceName the same on multiple rows but targetId, targetName will always be different.
I want to group all the target objects into the List for which source is the same.
I have List of Response objects and I am trying to perform stream() operation on it something like:
Map<Source, List<Target>> res = results
.stream()
.collect(Collectors.groupingBy(
Response::getSource)
//collect to map
So that my final output JSON would look something like:
"Response": {
"Source": {
"sourceId": "100",
"sourceName": "source1",
}
"Target": [{//grouping target objects with same source
"targetId": "10",
"targetName": "target1",
}, {
"targetId": "20",
"targetName": "target2",
}]
}