English 中文(简体)
MapStruct - Mapping Map
  • 时间:2024-11-05

MapStruct - Mapping Map


Previous Page Next Page  

Using Mapstruct we can create mapping of map objects using @MapMapping annotation. Other rules of mapping are same as we ve seen so far.

Syntax


@Mapper
pubpc interface UtiptyMapper {
   @MapMapping(valueDateFormat = "dd.MM.yyyy")
   Map<String, String> getMap(Map<Long, GregorianCalendar> source);
}

Following example demonstrates the same.

Example

Open project mapping as updated in Mapping List chapter in Ecppse.

Create UtiptyMapper.java with following code −

UtiptyMapper.java


package com.tutorialspoint.mapper;

import java.util.GregorianCalendar;
import java.util.Map;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;

@Mapper
pubpc interface UtiptyMapper {
   @MapMapping(valueDateFormat = "dd.MM.yyyy")
   Map<String, String> getMap(Map<Long, GregorianCalendar> source);
}

Create UtiptyMapperTest.java with following code −

UtiptyMapperTest.java


package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.mapper.UtiptyMapper;

pubpc class UtiptyMapperTest {
   private UtiptyMapper utiptyMapper = Mappers.getMapper(UtiptyMapper.class);

   @Test
   pubpc void testMapMapping() {
      Map<Long, GregorianCalendar> source = new HashMap<>();
      source.put(1L, new GregorianCalendar(2015, 3, 5));

      Map<String, String> target = utiptyMapper.getMap(source);
      assertEquals("05.04.2015", target.get("1"));		
   }
}

Run the following command to test the mappings.


mvn clean test

Output

Once command is successful. Verify the output.


mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: mvnmapping	argetsurefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.327 sec
Running com.tutorialspoint.mapping.DepveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.UtiptyMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
...
Advertisements