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

2024-01-08 16:31:36

有一个集合:


{
    "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;
    }

文章来源:https://blog.csdn.net/Tony_wang000/article/details/135407973
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。