Search code examples
javalistmappingdozer

Don't Map null entries from one list to another in Dozer


Suppose I have following Class - structure ?

class A{
List<B> listB;
//getter and setter
}
class B{
String s;
//getter and setter
}
//objectOfA has listB = [null,objectOfB,null]
A a2 = dozermapper.map(objectOfA,A.class);

I want a2 contains listB=[objectOfB] only. not null elements of list.

How to do it in dozer?


Solution

  • You could write a simple converter, like this (uses new converter api, you can use old also):

    public class Converter extends DozerConverter<List<B>, List<B>> {
      public Converter() {
        super(List.class, List.class);
      }
    
      public List<B> convertTo(List<B> source, List<B> destination) {
        List<B> result = new ArrayList<B>();
        for (B item : source) {
          if (item != null) {
              result.add(item); //or item copy, or whatever you want
          }
        }
        return result;
      }
    } 
    

    and then attach it to your mapping like this:

    <mapping>
      <class-a>yourpackage.A</class-a>
      <class-b>yourpackage.A</class-b>    
      <field custom-converter="yourpackage.Converter">
          <a>listB</a>
          <b>listB</b>
      </field>
    </mapping>