有一个集合:
{
"condition": [
"key3774","key3770"
],
"body": [
{
"key3779": "44406107.75",
"key3778": "-49468430.57",
"key3774": "一二三航",
"key3770": "SHY",
"key": "1742796948097728512"
},
{
"key3782": "634",
"key3775": "634",
"key3774": "一二三航",
"key3770": "SHY",
"key": "1742796948097728513"
},
{
"key3779": "971864954.96",
"key3778": "-98854650.65",
"key3774": "上航",
"key3770": "SHK",
"key": "1742796948097728514"
},
{
"key3782": "3921",
"key3775": "3921",
"key3774": "上航",
"key3770": "SHK",
"key": "1742796948097728515"
}
]
}
将该集合中的body,根据分组条件condition进行分组,后再聚合。
最终变为如下集合:
{
"condition": [
"key3774","key3770"
],
"body": [
{
"key3779": "44406107.75",
"key3778": "-49468430.57",
"key3774": "一二三航",
"key3770": "SHY",
"key": "1742796948097728512",
"key3782": "634",
"key3775": "634"
},
{
"key3779": "971864954.96",
"key3778": "-98854650.65",
"key3774": "上航",
"key3770": "SHK",
"key": "1742796948097728514",
"key3782": "3921",
"key3775": "3921"
}
]
}
执行代码:
private List<Map<String, String>> groupByCondition(List<Map<String, String>> body, List<String> conditionList) {
List<Map<String, String>> bodyRes = new ArrayList<>();
// 根据condition分组
Map<String, List<Map<String, String>>> recordMap = body.stream().collect(Collectors.groupingBy(map -> {
StringBuilder s = new StringBuilder();
conditionList.forEach(c -> {
if (s.length() != 0) {
s.append("#");
}
s.append(map.get(c));
});
return s.toString();
}));
// 分组后聚合
recordMap.forEach((k, v) -> {
if (CollectionUtils.isEmpty(v)) {
return;
}
if (v.size() > 1) {
// list有2个及以上,聚合
Map<String, String> mapRes = new HashMap<>();
v.forEach(mapRes::putAll);
bodyRes.add(mapRes);
} else {
// list有1个,直接取值
bodyRes.add(v.get(0));
}
});
return bodyRes;
}