Mapping two enums with same constant name

In this post under MapStruct, I will show with example how to map between two enums both having same constant name.

For our example, I will use the below two enums

ProcessStatus

package package11;

public enum ProcessStatus {
    RUNNING,
    PAUSE,
    CANCELLED,
    SHUTDOWN;
}

DisplayStatus

package package11;

public enum DisplayStatus {
    RUNNING,
    PAUSE,
    CANCELLED,
    SHUTDOWN;
}

I have to map enum constants from “ProcessStatus” to enum constant of “DisplayStatus”.

Please note the constant name in both enums are same. This is prerequisite for our example to work.

We create a mapper class as shown below

ProcessToDisplayStatusMapper

package package11;

import org.mapstruct.Mapper;

@Mapper
public interface ProcessToDisplayStatusMapper {
    DisplayStatus processStatusToDisplayStatusMap(ProcessStatus processStatus);
}

Below is the main class for your reference

Main class

package package11;

import org.mapstruct.factory.Mappers;

public class Example11 {
    public static void main(String[] args) {
        ProcessToDisplayStatusMapper processToDisplayStatusMapper = Mappers.getMapper(ProcessToDisplayStatusMapper.class);

        DisplayStatus displayStatus = processToDisplayStatusMapper.processStatusToDisplayStatusMap(ProcessStatus.RUNNING);
        System.out.println(displayStatus.getDeclaringClass() + ":" + displayStatus);
        displayStatus = processToDisplayStatusMapper.processStatusToDisplayStatusMap(ProcessStatus.PAUSE);
        System.out.println(displayStatus.getDeclaringClass() + ":" + displayStatus);
        displayStatus = processToDisplayStatusMapper.processStatusToDisplayStatusMap(ProcessStatus.CANCELLED);
        System.out.println(displayStatus.getDeclaringClass() + ":" + displayStatus);
        displayStatus = processToDisplayStatusMapper.processStatusToDisplayStatusMap(ProcessStatus.SHUTDOWN);
        System.out.println(displayStatus.getDeclaringClass() + ":" + displayStatus);
    }
}

Below is the output for your reference

Output

class package11.DisplayStatus:RUNNING
class package11.DisplayStatus:PAUSE
class package11.DisplayStatus:CANCELLED
class package11.DisplayStatus:SHUTDOWN

In this way we can map two enums with same constant name

Leave a comment