1. Overview

In this tutorial, we'll take a look at how to map collections of objects using MapStruct.

Since this article assumes already a basic understanding of MapStruct, beginners should check out our quick guide to MapStruct first.

2. Mapping Collections

In general, mapping collections with MapStruct works in the same way as for simple types.

Basically, we have to create a simple interface or abstract class and declare the mapping methods. Based on our declarations, MapStruct will generate the mapping code automatically. Typically, the generated code will loop over the source collection, convert each element to the target type, and include each of them in the target collection.

Let's take a look at a simple example.

2.1. Mapping Lists

First, for our example, let's consider a simple POJO as the mapping source for our mapper:

public class Employee {
    private String firstName;
    private String lastName;

    // constructor, getters and setters
}

The target will be a simple DTO:

public class EmployeeDTO {

    private String firstName;
    private String lastName;

    // getters and setters
}

Next, let's define our mapper:

@Mapper
public interface EmployeeMapper {
    List<EmployeeDTO> map(List<Employee> employees);
}

Finally, let's look at the code MapStruct generated from our EmployeeMapper interface:

public class EmployeeMapperImpl implements EmployeeMapper {

    @Override
    public List<EmployeeDTO> map(List<Employee> employees) {
        if (employees == null) {
            return null;
        }

        List<EmployeeDTO> list = new ArrayList<EmployeeDTO>(employees.size());
        for (Employee employee : employees) {
            list.add(employeeToEmployeeDTO(employee));
        }

        return list;
    }

    protected EmployeeDTO employeeToEmployeeDTO(Employee employee) {
        if (employee == null) {
            return null;
        }

        EmployeeDTO employeeDTO = new EmployeeDTO();

        employeeDTO.setFirstName(employee.getFirstName());
        employeeDTO.setLastName(employee.getLastName());

        return employeeDTO;
    }
}

There is an important thing to note. Specifically, MapStruct generated for us, automatically, the mapping from Employee to EmployeeDTO.

There are cases when this is not possible. For example, let's say we want to map our Employee model to the following model:

public class EmployeeFullNameDTO {

    private String fullName;

    // getter and setter
}

In this case, if we just declare the mapping method from a List of Employee to a List of EmployeeFullNameDTO we'll receive a compile-time error or warning like:

Warning:(11, 31) java: Unmapped target property: "fullName". 
  Mapping from Collection element "com.baeldung.mapstruct.mappingCollections.model.Employee employee" to 
  "com.baeldung.mapstruct.mappingCollections.dto.EmployeeFullNameDTO employeeFullNameDTO".

Basically, this means that MapStruct could not generate the mapping automatically for us in this case. Therefore, we need to define, manually, the mapping between Employee and EmployeeFullNameDTO.

Given these points, let's manually define it:

@Mapper
public interface EmployeeFullNameMapper {

    List<EmployeeFullNameDTO> map(List<Employee> employees);

    default EmployeeFullNameDTO map(Employee employee) {
        EmployeeFullNameDTO employeeInfoDTO = new EmployeeFullNameDTO();
        employeeInfoDTO.setFullName(employee.getFirstName() + " " + employee.getLastName());

        return employeeInfoDTO;
    }
}

The generated code will use the method we defined to map the elements of the source List to the target List.

This also applies in general. If we have defined a method that maps the source element type to the target element type, MapStruct will use it.

2.2. Mapping Sets and Maps

Mapping sets with MapStruct works in the same way as with lists. For example, let's say we want to map a Set of Employee instances to a Set of EmployeeDTO instances.

As before, we need a mapper:

@Mapper
public interface EmployeeMapper {

    Set<EmployeeDTO> map(Set<Employee> employees);
}

And MapStruct will generate the appropriate code:

public class EmployeeMapperImpl implements EmployeeMapper {

    @Override
    public Set<EmployeeDTO> map(Set<Employee> employees) {
        if (employees == null) {
            return null;
        }

        Set<EmployeeDTO> set = 
          new HashSet<EmployeeDTO>(Math.max((int)(employees.size() / .75f ) + 1, 16));
        for (Employee employee : employees) {
            set.add(employeeToEmployeeDTO(employee));
        }

        return set;
    }

    protected EmployeeDTO employeeToEmployeeDTO(Employee employee) {
        if (employee == null) {
            return null;
        }

        EmployeeDTO employeeDTO = new EmployeeDTO();

        employeeDTO.setFirstName(employee.getFirstName());
        employeeDTO.setLastName(employee.getLastName());

        return employeeDTO;
    }
}

The same applies to maps. Let's consider we want to map a Map<String, Employee> to a Map<String, EmployeeDTO>.

Then, we can follow the same steps as before:

@Mapper
public interface EmployeeMapper {

    Map<String, EmployeeDTO> map(Map<String, Employee> idEmployeeMap);
}

And MapStruct does its job:

public class EmployeeMapperImpl implements EmployeeMapper {

    @Override
    public Map<String, EmployeeDTO> map(Map<String, Employee> idEmployeeMap) {
        if (idEmployeeMap == null) {
            return null;
        }

        Map<String, EmployeeDTO> map = new HashMap<String, EmployeeDTO>(Math.max((int)(idEmployeeMap.size() / .75f) + 1, 16));

        for (java.util.Map.Entry<String, Employee> entry : idEmployeeMap.entrySet()) {
            String key = entry.getKey();
            EmployeeDTO value = employeeToEmployeeDTO(entry.getValue());
            map.put(key, value);
        }

        return map;
    }

    protected EmployeeDTO employeeToEmployeeDTO(Employee employee) {
        if (employee == null) {
            return null;
        }

        EmployeeDTO employeeDTO = new EmployeeDTO();

        employeeDTO.setFirstName(employee.getFirstName());
        employeeDTO.setLastName(employee.getLastName());

        return employeeDTO;
    }
}

3. Collections Mapping Strategies

Often, we need to map data types having a parent-child relationship. Typically, we have a data type (parent) having as field a Collection of another data type (child).

For such cases, MapStruct offers a way to choose how to set or add the children to the parent type. In particular, the @Mapper annotation has a collectionMappingStrategy attribute which can be ACCESSOR_ONLY, SETTER_PREFERRED, ADDER_PREFERRED or TARGET_IMMUTABLE.

All these values refer to the way the children should be set or added to the parent type. The default value is ACCESSOR_ONLY, which means that only accessors can be used to set the Collection of children.

This option comes in handy when the setter for the Collection field is not available but we have an adder. Another case in which this is useful is when the Collection is immutable on the parent type. Usually, we encounter these cases in generated target types.

3.1. ACCESSOR_ONLY Collection Mapping Strategy

Let's take an example to better understand how this works.

For our example, let's create a Company class as our mapping source:

public class Company {

    private List<Employee> employees;

   // getter and setter
}

And the target for our mapping will be a simple DTO:

public class CompanyDTO {

    private List<EmployeeDTO> employees;

    public List<EmployeeDTO> getEmployees() {
        return employees;
    }

    public void setEmployees(List<EmployeeDTO> employees) {
        this.employees = employees;
    }

    public void addEmployee(EmployeeDTO employeeDTO) {
        if (employees == null) {
            employees = new ArrayList<>();
        }

        employees.add(employeeDTO);
    }
}

Note that we have both the setter, setEmployees, and the adder, addEmployee, available. Also, for the adder, we are responsible for collection initialization.

Now, let's say we want to map a Company to a CompanyDTO. Then, as before we need a mapper:

@Mapper(uses = EmployeeMapper.class)
public interface CompanyMapper {
    CompanyDTO map(Company company);
}

Note that we reused the EmployeeMapper and the default collectionMappingStrategy.

Now, let's take a look at the code MapStruct generated:

public class CompanyMapperImpl implements CompanyMapper {

    private final EmployeeMapper employeeMapper = Mappers.getMapper(EmployeeMapper.class);

    @Override
    public CompanyDTO map(Company company) {
        if (company == null) {
            return null;
        }

        CompanyDTO companyDTO = new CompanyDTO();

        companyDTO.setEmployees(employeeMapper.map(company.getEmployees()));

        return companyDTO;
    }
}

As can be seen, MapStruct uses the setter, setEmployees, to set the List of EmployeeDTO instances. This happens because here we use the default collectionMappingStrategy, ACCESSOR_ONLY.

Also, MapStruct found a method mapping a List<Employee> to a List<EmployeeDTO> in EmployeeMapper and reused it.

3.2. ADDER_PREFERRED Collection Mapping Strategy

In contrast, let's consider we used ADDER_PREFERRED as collectionMappingStrategy:

@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED,
        uses = EmployeeMapper.class)
public interface CompanyMapperAdderPreferred {
    CompanyDTO map(Company company);
}

Again, we want to reuse the EmployeeMapper. However, we need to explicitly add a method that can convert a single Employee to an EmployeeDTO first:

@Mapper
public interface EmployeeMapper {
    EmployeeDTO map(Employee employee);
    List map(List employees);
    Set map(Set employees);
    Map<String, EmployeeDTO> map(Map<String, Employee> idEmployeeMap);
}

This is because MapStruct will use the adder to add EmployeeDTO instances to the target CompanyDTO instance one by one:

public class CompanyMapperAdderPreferredImpl implements CompanyMapperAdderPreferred {

    private final EmployeeMapper employeeMapper = Mappers.getMapper( EmployeeMapper.class );

    @Override
    public CompanyDTO map(Company company) {
        if ( company == null ) {
            return null;
        }

        CompanyDTO companyDTO = new CompanyDTO();

        if ( company.getEmployees() != null ) {
            for ( Employee employee : company.getEmployees() ) {
                companyDTO.addEmployee( employeeMapper.map( employee ) );
            }
        }

        return companyDTO;
    }
}

In case the adder was not available, the setter would have been used.

We can find a complete description of all the collection mapping strategies in MapStruct's reference documentation.

4. Implementation Types for Target Collection

MapStruct supports collections interfaces as target types to mapping methods.

In this case, some default implementations are used in the generated code. For example, the default implementation for List is ArrayList as can be noted from our examples above.

We can find the complete list of interfaces MapStruct supports and the default implementations it uses for each interface, in the reference documentation.

5. Conclusion

In this article, we've explored how to map collections using MapStruct.

First, we've looked at how we can map different types of collections. Then, we saw how we can customize parent-child relationships mappers, using collection mapping strategies.

Along the way, we highlighted the key points and things to keep in mind while mapping collections using MapStruct.

As usual, the complete code is available over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!