Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll learn how to map collections of objects using MapStruct.

Since this article already assumes 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 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, we’ll 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, we’ll 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;
    }
}

One important thing to note is that MapStruct automatically generated the mapping from Employee to EmployeeDTO for us.

There are cases when this isn’t 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:

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, in this case, MapStruct couldn’t generate the mapping automatically for us. Therefore, we need to manually define 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’ve 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);
}

Then 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 suppose we want to map a Map<String, Employee> to a Map<String, EmployeeDTO>.

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) that has as a 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 that can be ACCESSOR_ONLY, SETTER_PREFERRED, ADDER_PREFERRED or TARGET_IMMUTABLE.

All of 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 isn’t available, but we have an adder. Another case where 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 look at an example to better understand how this works.

We’ll create a Company class as our mapping source:

public class Company {

    private List<Employee> employees;

   // getter and setter
}

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 we can see, MapStruct uses the setter, setEmployees, to set the List of EmployeeDTO instances. This happens because we used the default collectionMappingStrategy, ACCESSOR_ONLY.

MapStruct also 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 suppose we used ADDER_PREFERRED as the 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;
    }
}

If the adder is unavailable, the setter will be 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 explored how to map collections using MapStruct.

First, we looked at how to map different types of collections. Then, we learned how to customize parent-child relationship 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.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.