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))
}
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With