Mapping two enums with different constant name

In this post under MapStruct I will show with example how to map two enums having different constant name.

For our example lets say you have to map below enum

Day

package package12;

public enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY;
}

to below enum

Week

package package12;

public enum Week {
    WEEK_DAY,
    WEEK_END;
}

We will create below mapper interface

package package12;

import org.mapstruct.Mapper;
import org.mapstruct.ValueMapping;
import org.mapstruct.ValueMappings;

@Mapper
public interface DayToWeekMapper {
    @ValueMappings({
            @ValueMapping(source = "MONDAY", target = "WEEK_DAY"),
            @ValueMapping(source = "TUESDAY", target = "WEEK_DAY"),
            @ValueMapping(source = "WEDNESDAY", target = "WEEK_DAY"),
            @ValueMapping(source = "THURSDAY", target = "WEEK_DAY"),
            @ValueMapping(source = "FRIDAY", target = "WEEK_DAY"),
            @ValueMapping(source = "SATURDAY", target = "WEEK_END"),
            @ValueMapping(source = "SUNDAY", target = "WEEK_END")
    })
    Week dayToWeekMapping(Day day);
}

In the above interface, using “@ValueMapping” annotation we are explicity setting each enum values from “Day” enum to “Week” enum values.

Enum values from “MONDAY” to “FRIDAY” are mapped to “WEEK_DAY”. Whereas “SATURDAY” and “SUNDAY” are mapped to “WEEK_END”.

Below is the main class that shows how to use the interface

Main class

package package12;

import org.mapstruct.factory.Mappers;

public class Example12 {
    public static void main(String[] args) {
        DayToWeekMapper dayToWeekMapper = Mappers.getMapper(DayToWeekMapper.class);

        Week week = dayToWeekMapper.dayToWeekMapping(Day.MONDAY);
        System.out.println(week);
        week = dayToWeekMapper.dayToWeekMapping(Day.SATURDAY);
        System.out.println(week);
    }
}

In this way we can map two enums having different constant names.

Leave a comment