You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中遍历查询结果列表并按key值分组创建新对象的实现方案

实现方案

前置准备

先确认你的MyObject和MyCreatedObject已经提供了对应属性的getter、setter方法,以及MyCreatedObject的全参数构造方法/无参构造方法。这里默认你代码里的Value1就是String类型、Value2就是Integer类型(和MyObject的属性类型对应),如果是自定义类型自行替换即可。

方案1:普通遍历实现(兼容性好,JDK所有版本都可用)

// 原始查询结果列表
List<MyObject> originalList = yourQueryResult;
// 临时存储分组结果的Map
Map<String, MyCreatedObject> tempMap = new HashMap<>();

for (MyObject obj : originalList) {
    String key = obj.getKey();
    // 如果key不存在,先初始化MyCreatedObject
    MyCreatedObject createdObj = tempMap.computeIfAbsent(key, k -> {
        MyCreatedObject newObj = new MyCreatedObject();
        newObj.setKey(k);
        newObj.setValue1List(new ArrayList<>());
        newObj.setValue2List(new ArrayList<>());
        return newObj;
    });
    // 把当前对象的属性加入对应列表
    createdObj.getValue1List().add(obj.getValue1());
    createdObj.getValue2List().add(obj.getValue2());
}

// 转成结果列表
List<MyCreatedObject> result = new ArrayList<>(tempMap.values());

方案2:Stream流实现(JDK8+支持,代码更简洁)

List<MyCreatedObject> result = originalList.stream()
    // 按key分组
    .collect(Collectors.groupingBy(MyObject::getKey))
    .entrySet().stream()
    .map(entry -> {
        String key = entry.getKey();
        // 收集当前key对应的所有value1
        List<String> value1List = entry.getValue().stream()
                .map(MyObject::getValue1)
                .collect(Collectors.toList());
        // 收集当前key对应的所有value2
        List<Integer> value2List = entry.getValue().stream()
                .map(MyObject::getValue2)
                .collect(Collectors.toList());
        // 构造MyCreatedObject
        return new MyCreatedObject(key, value1List, value2List);
    })
    .collect(Collectors.toList());

如果需要保持原始列表中key的出现顺序,可以把groupingBy替换为Collectors.groupingBy(MyObject::getKey, LinkedHashMap::new, Collectors.toList())即可。

内容的提问来源于stack exchange,提问作者Matheus Vellner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 07:15:02