企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
集合映射与普通的实体类映射都是一样的。 **1. 两个实体类** ```java @Data public class Cow { private Integer id; private String name; public Cow(Integer id, String name) { this.id = id; this.name = name; } } @Data public class CowDto { private Integer id; private String name; } ``` **2. 映射接口** ```java @Mapper public interface CowMapper { CowMapper INSTANCE = Mappers.getMapper(CowMapper.class); List<CowDto> toDtoList(List<Cow> source); Set<CowDto> toDtoSet(Set<Cow> source); Map<Integer, CowDto> toDtoMap(Map<Integer, Cow> source); } ``` **3. 测试** ```java @Test public void testCowMapper() { List<Cow> cowList = new ArrayList<>(); Set<Cow> cowSet = new HashSet<>(); Map<Integer, Cow> cowMap = new HashMap<>(); cowList.add(new Cow(1001, "张三")); cowSet.add(new Cow(1002, "李四")); cowMap.put(1003, new Cow(1003, "王五")); List<CowDto> cowDtoList = CowMapper.INSTANCE.toDtoList(cowList); Set<CowDto> cowDtoSet = CowMapper.INSTANCE.toDtoSet(cowSet); Map<Integer, CowDto> cowDtoMap = CowMapper.INSTANCE.toDtoMap(cowMap); //CowList:[Cow(id=1001, name=张三)] System.out.println("CowList:" + cowList); //CowDtoList:[CowDto(id=1001, name=张三)] System.out.println("CowDtoList:" + cowDtoList); //CowSet:[Cow(id=1002, name=李四)] System.out.println("CowSet:" + cowSet); //CowDtoSet:[CowDto(id=1002, name=李四)] System.out.println("CowDtoSet:" + cowDtoSet); //CowMap:{1003=Cow(id=1003, name=王五)} System.out.println("CowMap:" + cowMap); //CowDtoMap:{1003=CowDto(id=1003, name=王五)} System.out.println("CowDtoMap:" + cowDtoMap); } ``` **4. 查看映射接口被Mapstruct编译后的代码** ```java public class CowMapperImpl implements CowMapper { public CowMapperImpl() { } public List<CowDto> toDtoList(List<Cow> source) { if (source == null) { return null; } else { List<CowDto> list = new ArrayList(source.size()); Iterator var3 = source.iterator(); while(var3.hasNext()) { Cow cow = (Cow)var3.next(); list.add(this.cowToCowDto(cow)); } return list; } } public Set<CowDto> toDtoSet(Set<Cow> source) { if (source == null) { return null; } else { Set<CowDto> set = new HashSet(Math.max((int)((float)source.size() / 0.75F) + 1, 16)); Iterator var3 = source.iterator(); while(var3.hasNext()) { Cow cow = (Cow)var3.next(); set.add(this.cowToCowDto(cow)); } return set; } } public Map<Integer, CowDto> toDtoMap(Map<Integer, Cow> source) { if (source == null) { return null; } else { Map<Integer, CowDto> map = new HashMap(Math.max((int)((float)source.size() / 0.75F) + 1, 16)); Iterator var3 = source.entrySet().iterator(); while(var3.hasNext()) { Entry<Integer, Cow> entry = (Entry)var3.next(); Integer key = (Integer)entry.getKey(); CowDto value = this.cowToCowDto((Cow)entry.getValue()); map.put(key, value); } return map; } } protected CowDto cowToCowDto(Cow cow) { if (cow == null) { return null; } else { CowDto cowDto = new CowDto(); cowDto.setId(cow.getId()); cowDto.setName(cow.getName()); return cowDto; } } } ```