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

MapStruct如何有条件排除集合中theDate为过去时间的ChildDTO

MapStruct过滤列表中符合条件的元素

@Mapping注解无法直接实现集合元素的过滤逻辑,你可以通过以下两种方式实现需求:

方法一:自定义列表映射方法

在ParentMapper中声明默认方法,同时完成子实体到DTO的映射和过滤:

@Mapper(uses = {ChildMapper.class})
public interface ParentMapper {
    ParentDTO entityToDTO(ParentEntity parent);

    // 自定义映射+过滤逻辑
    default List<ChildDTO> mapAndFilterChildren(List<ChildEntity> children) {
        if (children == null) {
            return null;
        }
        return children.stream()
                .map(ChildMapper.INSTANCE::entityToDTO)
                .filter(childDTO -> childDTO.getTheDate().isAfter(Instant.now()))
                .collect(Collectors.toList());
    }
}

MapStruct会自动识别该方法,替代默认的列表映射逻辑,直接返回过滤后的子DTO列表。

方法二:使用@AfterMapping后置处理

先完成全量对象映射,再对ParentDTO中的子列表做过滤:

@Mapper(uses = {ChildMapper.class})
public interface ParentMapper {
    ParentDTO entityToDTO(ParentEntity parent);

    @AfterMapping
    default void filterPastDateChildren(@MappingTarget ParentDTO parentDTO) {
        List<ChildDTO> children = parentDTO.getChildren();
        if (children == null || children.isEmpty()) {
            return;
        }
        List<ChildDTO> filtered = children.stream()
                .filter(childDTO -> childDTO.getTheDate().isAfter(Instant.now()))
                .collect(Collectors.toList());
        parentDTO.setChildren(filtered);
    }
}

这种方式适合需要先完成全量映射,再做后续处理的场景。

注意事项

  • 必须处理null场景,避免空指针异常
  • 如果项目使用Spring,可以注入ChildMapper实例,替代ChildMapper.INSTANCE
  • Instant.now()的时区可根据业务需求调整为指定时区的当前时间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:25:24