Java可变长度字段分组

import java.util.*;
import java.util.stream.Collectors;

public class GroupByDemo {

    public static void main(String[] args) {
        List<Map<String, Object>> data = getData(); // 获取数据

        List<String> groupByFields = Arrays.asList("d", "e"); // 可变长度的group by字段

        Map<List<Object>, List<Map<String, Object>>> groupedData = data.stream()
                .collect(Collectors.groupingBy(row -> groupByFields.stream()
                        .map(row::get)
                        .collect(Collectors.toList())));

        groupedData.forEach((key, value) -> {
            System.out.println("Group Key: " + key);
            System.out.println("Grouped Data: " + value);
            System.out.println();
        });
    }

    // 模拟数据
    private static List<Map<String, Object>> getData() {
        List<Map<String, Object>> data = new ArrayList<>();

        Map<String, Object> row1 = new HashMap<>();
        row1.put("a", "group1");
        row1.put("b", "group2");
        row1.put("c", "group3");
        row1.put("d", "group4");
        row1.put("e", "value1");
        data.add(row1);

        Map<String, Object> row2 = new HashMap<>();
        row2.put("a", "group1");
        row2.put("b", "group2");
        row2.put("c", "group3");
        row2.put("d", "group4");
        row2.put("e", "value2");
        data.add(row2);

        Map<String, Object> row3 = new HashMap<>();
        row3.put("a", "group1");
        row3.put("b", "group2");
        row3.put("c", "group3");
        row3.put("d", "group5");
        row3.put("e", "value3");
        data.add(row3);

        return data;
    }
}

 输出结果:

Group Key: [group4, value1]
Grouped Data: [{a=group1, b=group2, c=group3, d=group4, e=value1}]

Group Key: [group5, value3]
Grouped Data: [{a=group1, b=group2, c=group3, d=group5, e=value3}]

Group Key: [group4, value2]
Grouped Data: [{a=group1, b=group2, c=group3, d=group4, e=value2}]

 

posted @ 2023-09-13 08:37  静默之尘  阅读(14)  评论(0编辑  收藏  举报