In this post under MapStruct, I will show with example how to map values of Map to a bean.
In our example we use map a Map to “StudentDTO” object.
Below is the class structure of “StudentDTO” class.
StudentDTO
package package7;
public class StudentDTO {
private Integer id;
private String name;
private String className;
//Removed getter, setter, and toString method for brevity
}
Below is the class structure for “StudentMapper” interface
StudentMapper interface
package package7;
import org.mapstruct.Mapper;
import java.util.Map;
@Mapper
public interface StudentMapper {
StudentDTO getDTOFromMap(Map<String, String> map);
}
In the above code, we annotate the interface “StudentMapper” with “@Mapper” annotation.
Add a method named “getDTOFromMap” which takes a “Map” instance as an argument and returns an instance of “StudentDTO” class.
Here the attribute names of “StudentDTO” class will be same as key names in the Map. So we don’t need “@Mapping” annotation.
Below is the complete code for your reference.
Main class
1 package package7;
2
3 import org.mapstruct.Mapper;
4 import org.mapstruct.factory.Mappers;
5
6 import java.util.HashMap;
7 import java.util.Map;
8
9 public class Example7 {
10 public static void main(String[] args) {
11 Map<String, String> map = new HashMap<>(0);
12 map.put("id", "1");
13 map.put("name", "John Doe");
14 map.put("className", "Second");
15
16 StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);
17
18 StudentDTO studentDTO = studentMapper.getDTOFromMap(map);
19
20 System.out.println(studentDTO);
21 }
22 }
In the above code, from line 11 to 14, I create a Map instance and populate it with key and value pair.
Make sure that the key names in map are equal to “StudentDTO” attribute names. For example, the key “className” is equal to attribute “className” in “StudentDTO” class.
The Mapper framework will use these key names to find the properties in the destination object.
The Mapper framework assumes that there is a property in destination object with name equals to Map key name.
If there is a difference between map key name and object attribute name then we must use “@Mapping” interface in “StudentMapper” interface.
At line 16, get an instance of “StudentMapper” interface.
At line 18, I call “getDTOFromMap” method available on “StudentMapper” interface and pass the map created at line 11 as an argument.
The result of this method call is “StudentDTO” instance with values copied from “Map”.
In this way we can map a “Map” to an object.
Below is the output for your reference
Output
1:John Doe:Second