【发布时间】:2022-01-15 07:07:35
【问题描述】:
我的课程类似于:
class Response {
Source source;
Target target;
}
class Source {
Long sourceId;
String sourceName;
}
class Target {
Long regionId;
String regionName;
Long countryId;
String countryName;
}
在响应中,source(sourceId,sourceName) 对于不同的 Target 对象可能是相同的。
同样,我还想根据regionId 和regionName 在Target 对象中进行分组。
对于regionId 和regionName 的组合,我们可以在目标对象中包含List 或countries。
我在数据库中有这 6 个属性 sourceId, sourceName, targetId, targetName,countryId,countryName 的条目。我可以在多行上使用相同的 sourceId, sourceName,但 target 总是不同的。
我想将所有目标对象分组到源相同的列表中。
我有响应对象列表,我正在尝试对其执行 stream() 操作,例如:
List<Response> responses; // set up the input list
List<FinalResponse> finalResponseLst = responses.stream()
.collect(Collectors.groupingBy(
Response::getSource,
Collectors.mapping(Response::getTarget, Collectors.toList())
))
.entrySet()
.stream()
.map(e -> new FinalResponse(e.getKey(), e.getValue()))
.collect(Collectors.toList());
这给了我Source 和它们各自的Target 对象。但是如何根据地区对目标对象内的国家进行分组呢?如何为单个Target 对象创建具有相同地区的国家/地区列表。
所以我的最终输出 JSON 看起来像:
Response": {
"Source": {
"sourceId": "100",
"sourceName": "source1",
},
"Targets": [
{
"TargetRegion":{//grouping target objects with same regions
"regionId": "100",
"regionName": "APAC",
},
"TargetCountries":[{
"countryId": "1",
"countryName": "USA",
},
{
"targetId": "2",
"targetName": "China",
},
{
"targetId": "3",
"targetName": "Brazil"
}
]
},
{
"TargetRegion":{//grouping target objects with same regions
"regionId": "200",
"regionName": "ASPAC",
},
"TargetCountries":[{
"countryId": "11",
"countryName": "Japan",
},
{
"targetId": "22",
"targetName": "Combodia",
},
{
"targetId": "33",
"targetName": "Thailand"
}
]
}
]
}
【问题讨论】:
标签: java collections java-8 java-stream java-11