Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Lists of objects with Dozer

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))
}
like image 874
user1323246 Avatar asked Jan 17 '13 15:01

user1323246


People also ask

What is Dozer mapping?

Overview. Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to another, attribute by attribute. The library not only supports mapping between attribute names of Java Beans, but also automatically converts between types – if they're different.

Does ModelMapper use reflection?

I believe that ModelMapper is based on reflection and performs the mapping during runtime. Whereas MapStruct is a code generator which generates the mapping code (java classes) during compilation time. So naturally if you are worried about performance then MapStruct is the clear choice.

What is bean mapping?

It is mainly bean to bean mapper that recursively copies data from one java object to another java object – attribute by attribute. We realize it's full capability when We are dealing with deeply-nested complex java beans, which we are easily seen in large enterprise applications.


2 Answers

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.

like image 68
artbristol Avatar answered Sep 20 '22 17:09

artbristol


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);
like image 45
MatthiasLaug Avatar answered Sep 21 '22 17:09

MatthiasLaug