Mapping Lists of objects with Dozer
Asked Answered
Y

2

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))
}
Yttrium answered 17/1, 2013 at 15:54 Comment(0)
M
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.

Myrick answered 17/1, 2013 at 15:59 Comment(0)
S
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);
Skyward answered 19/2, 2013 at 17:40 Comment(1)
wouldn't it be more correct to add the generics to s1 list? like List s1<U> = new ArrayList();Boult

© 2022 - 2024 — McMap. All rights reserved.