13

I created a dozer mapping for ClassA to ClassB.

Now I want to map a List<ClassA> to a List<ClassB>.

Is it possible to just

mapper.map(variableListClassA, variableListClassB) 

or do I have to go over a loop, e.g.

for (ClassA classA : variableListClassA) {
    variableListClassB.add(mapper.map(classA, ClassB.class))
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
user1323246
  • 433
  • 2
  • 6
  • 23

2 Answers2

14

You need to use the loop, because the type of the list is erased at runtime.

If both lists are a field of a class, you can map the owning classes.

artbristol
  • 32,010
  • 5
  • 70
  • 103
13

you could also use A helper class to do that in one step

public class DozerHelper {

    public static <T, U> ArrayList<U> map(final Mapper mapper, final List<T> source, final Class<U> destType) {

        final ArrayList<U> dest = new ArrayList<U>();

        for (T element : source) {
        if (element == null) {
            continue;
        }
        dest.add(mapper.map(element, destType));
    }

    // finally remove all null values if any
    List s1 = new ArrayList();
    s1.add(null);
    dest.removeAll(s1);

    return dest;
}
}

and your call above would be like

List<ClassB> listB = DozerHelper.map(mapper, variableListClassA, ClassB.class);
copakawusau
  • 145
  • 1
  • 9
MatthiasLaug
  • 2,924
  • 6
  • 28
  • 43