How to map enum to enum with the same keys in Java. For example..
public enum FirstEnum {
A, B
}
public enum ScndEnum {
A, B, C
}
I couldnt find good solution
You can't map directly from one enum type to another, but you can use the value of name() and map it using valueOf(). Both of these methods come with all enum classes:
ScndEnum aToA = ScndEnum.valueOf(FirstEnum.A.name());
And if you want to make that generic:
private static <E extends Enum<E>, F extends Enum<F>>
F mapEnum(E enum1, Class<F> enum2Class) {
return Enum.valueOf(enum2Class, enum1.name());
}
Which you can call using something like
ScndEnum b = mapEnum(FirstEnum.B, ScndEnum.class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With