首页 > 解决方案 > Mapstruct:将对象内部的列表映射到对象列表

问题描述

鉴于:

public class Car {
  private String plate;
  private List<String> tires;
}

public class TirePlate {
  private String plate;
  private String tire;
}

我想将所有 Car.tires 映射到单独的 TirePlates 中。我知道我可以制作一个映射器List<String>List<tires>但如果我这样做了,我会失去盘子。

怎么把盘子放进去?

标签: javamapstruct

解决方案


您可以做的是为将获取的列表创建一个自定义映射器,plate然后您将有一个自定义方法映射platetire一个TirePlate.

例如:

@Mapper
public interface TireMapper {

    CarDto map(Car car);

    default List<TirePlate> map(List<String> tires, String plate) {
        List<TirePlate> tirePlates = new ArrayList<>(tires.size());

        for(String tire: tires) {
            tirePlates.add(map(tire, plate));
        }
        return tirePlates;
    }

    TirePlate map(String tire, String plate);
}

推荐阅读