1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| package com.example;
import org.modelmapper.AbstractConverter; import org.modelmapper.Condition; import org.modelmapper.ModelMapper; import org.modelmapper.PropertyMap; import org.modelmapper.convention.MatchingStrategies;
import java.util.ArrayList; import java.util.List; import java.util.Objects;
public class App {
public static void main(String[] args) {
List<DtoA> aList = new ArrayList<>(); DtoA a1 = new DtoA(1, "1", "1"); DtoA a2 = new DtoA(2, "2", "2"); aList.add(a1); aList.add(a2);
PropertyMap<DtoA, DtoB> propertyMap = new PropertyMap<>() { @Override protected void configure() { using(new AbstractConverter<Integer, Integer>() { @Override protected Integer convert(Integer source) { return source == 2 ? 22 : source; } }).map(source.getUserNo(), destination.getUserNo());
using(new AbstractConverter<String, String>() { @Override protected String convert(String source) { return Objects.equals(source, "2") ? "22" : source; } }).map(source.getUserName(), destination.getUserName());
Condition<String, String> passwordCondition = ctx -> "2".equals(ctx.getSource()); when(passwordCondition).map(source.getUserPassword(), destination.getUserPassword()); } };
List<DtoB> result = new App().mapList(aList, DtoB.class, propertyMap); for (DtoB tmDtoB : result) { System.out.println(tmDtoB); } }
public <S, T> List<T> mapList(List<S> source, Class<T> targetClass, PropertyMap<S, T> propertyMap) { ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setFieldMatchingEnabled(true); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); if (propertyMap != null) { modelMapper.addMappings(propertyMap); } return source.stream().map(element -> modelMapper.map(element, targetClass)).toList(); } }
|