I faced the same problem and I found out the "Enum" in the name class is indeed misleading.
Anyway, even if you could use an Enum, it would be useless for you since you have custom attributes.
But, you can workaround this problem iterating over the enum values and filling the map. One generic way is creating an interface like this:
public interface CodeNameEnum {
String getCode();
String getName();
}
Then, make you enum implement it:
public enum PointInTimeType implements CodeNameEnum {
FIRST("F", "First"),
START("S", "Start"),
END("E", "End"),
LAST("L", "Last"),
MIN("MI", "Minimum"),
MAX("MX", "Maximum");
private String code;
private String name;
private PointInTimeType(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
}
Finally, use this method:
public class EnumToMap {
public static Map<String, String> getMapFromEnum(CodeNameEnum[] codeNameEnumArray) {
Map <String, String> map = new HashMap<String, String>();
for (CodeNameEnum codeNameEnum : codeNameEnumArray) {
map.put(codeNameEnum.getCode(), codeNameEnum.getName());
}
return map;
}
public static void main(String[] args) {
Map <String, String> map = getMapFromEnum(PointInTimeType.values());
System.out.println(map);
}
}
So you can use this method for every enum containing code and name.
Otherwise, if it's a isolated case, just do this:
Map <String, String> map = new HashMap<String, String>();
for (PointInTimeType item : PointInTimeType.values()) {
map.put(item.getCode(), item.getName());
}
return map;