java使用stream流进行分组并求和

时间:2025-04-02 19:52:18

示例代码:

    @Test
    public void Test1() {
        List<Map<String, Object>> data = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        ("a", "A1");
        ("b", "B1");
        ("c", new BigDecimal(100));
        ("d", new BigDecimal(50));
        (map1);

        Map<String, Object> map2 = new HashMap<String, Object>();
        ("a", "A1");
        ("b", "B1");
        ("c", new BigDecimal(200));
        ("d", new BigDecimal(20));
        (map2);

        Map<String, Object> map3 = new HashMap<String, Object>();
        ("a", "A2");
        ("b", "B1");
        ("c", new BigDecimal(300));
        ("d", new BigDecimal(150));
        (map3);

        Map<String, Object> map4 = new HashMap<String, Object>();
        ("a", "A2");
        ("b", "B2");
        ("c", new BigDecimal(400));
        ("d", new BigDecimal(70));
        (map4);

        Map<String, Object> map5 = new HashMap<String, Object>();
        ("a", "A3");
        ("b", "B2");
        ("c", new BigDecimal(50));
        ("d", new BigDecimal(50));
        (map5);

        //对a和b字段进行分组,且对c和d字段进行求和
        Map<String, List<Map<String, Object>>> result = ()
                .collect((map -> ("a") + "_" + ("b")))
                .entrySet().stream()
                .collect((::getKey, entry -> {
                    BigDecimal sumC = ().stream()
                            .map(map -> (BigDecimal) ("c"))
                            .reduce(, BigDecimal::add);
                    BigDecimal sumD = ().stream()
                            .map(map -> (BigDecimal) ("d"))
                            .reduce(, BigDecimal::add);
                    ().forEach(map -> {
                        ("sumB", sumC);
                        ("sumC", sumD);
                    });
                    return ();
                }));
         // 输出结果
        (result);

    }