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

Java不使用第三方映射工具实现DTO列表转Entity列表的问题咨询

实现代码

如果你的需求是直接从Dto列表生成全新的Entity列表,仅按规则替换指定字段,其余字段原样从Dto复制,实现如下:

private List<AddressEntity> convertDtoToEntity(List<AddressDto> aDto) {
    // 先初始化返回列表,避免空指针异常
    List<AddressEntity> newAddressEntityList = new ArrayList<>();
    for (AddressDto dto : aDto) {
        AddressEntity entity = new AddressEntity();
        // 无需修改的字段直接赋值
        entity.setUnitNo(dto.getUnitNo());
        entity.setFloorNo(dto.getFloorNo());
        
        // 处理buildingName替换规则:Green替换为Grove
        String buildingName = dto.getBuildingName();
        entity.setBuildingName("Green".equals(buildingName) ? "Grove" : buildingName);
        
        // 处理areaName替换规则:BR替换为Tampa
        String areaName = dto.getAreaName();
        entity.setAreaName("BR".equals(areaName) ? "Tampa" : areaName);
        
        newAddressEntityList.add(entity);
    }
    return newAddressEntityList;
}

如果你需要保留已有addressEntityList的unitNo、floorNo原值不变,仅同步Dto列表的字段做规则替换,就需要按索引同步遍历两个列表,实现如下:

// 方法入参新增已有Entity列表
private List<AddressEntity> convertDtoToEntity(List<AddressDto> aDto, List<AddressEntity> existEntityList) {
    // 提前校验长度一致,避免索引越界
    if (aDto.size() != existEntityList.size()) {
        throw new IllegalArgumentException("Dto列表与Entity列表长度不匹配");
    }
    List<AddressEntity> newAddressEntityList = new ArrayList<>();
    // 用普通for循环按索引同步遍历两个列表
    for (int i = 0; i < aDto.size(); i++) {
        AddressDto dto = aDto.get(i);
        AddressEntity entity = existEntityList.get(i);
        
        // unitNo、floorNo保留Entity原有值,无需修改
        // 仅按规则更新指定字段
        String buildingName = dto.getBuildingName();
        entity.setBuildingName("Green".equals(buildingName) ? "Grove" : buildingName);
        
        String areaName = dto.getAreaName();
        entity.setAreaName("BR".equals(areaName) ? "Tampa" : areaName);
        
        newAddressEntityList.add(entity);
    }
    return newAddressEntityList;
}

// 调用时传入两个列表即可
List<AddressEntity> addressEntityListResult=convertDtoToEntity(addressDtoList, addressEntityList);

注意事项

  • 字符串比较使用"常量".equals(变量)的写法,可避免变量为null时触发空指针异常
  • 同步遍历两个列表必须提前校验长度一致,否则会出现索引越界问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 22:36:06