Java 8的Stream API分组。将List<Map<String, String>>集合分组,分组条件为动态集合List<String>

有一个集合:


{
    "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> groupByCondition(List> body, List conditionList) {

        List> bodyRes = new ArrayList<>();

        // 根据condition分组
        Map>> 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 mapRes = new HashMap<>();
                v.forEach(mapRes::putAll);
                bodyRes.add(mapRes);
            } else {
                // list有1个,直接取值
                bodyRes.add(v.get(0));
            }
        });

        return bodyRes;
    }

你可能感兴趣的:(java,list)