'How to create a map with enum values in java?
I need to validate the value of a parameters passed as part of REST API. These parameters are a fixed set of values. I thought of using a map having parameter name as key and enum as value. So I can check if the value sent in REST API is one of the enum keys.
But I am not able to create a Map with String key and enum value in java, tried creating Map and then putting and enum as value, but it fails.
class Validation {
enum Type {
INTERNAL,
EXTERNAL
};
}
Map<String, Object> validationMap = new HashMap<String, Object>();
validationMap.put("type", Validation.Type);
This is throwing an error that type is not defined.
Solution 1:[1]
This is probably what you're looking for, Map<String, Object> is changed to Map<String, Validation.type>:
Map<String, Validation.type> validationMap = new HashMap<String, Validation.type>();
validationMap.put("type", Validation.type.INTERNAL);
validationMap.put("type2", Validation.type.EXTERNAL);
Your original code would have worked, if you had changed Validation.type to Validation.type.INTERNAL for example, however your validationMap map allows the storage of any Object, so validationMap.put("type2", 123.123); would also have worked, which is unlikely to be something you want.
Solution 2:[2]
Is this what you need?
Map<String, List<Validation.type>> validationMap = new HashMap<>();
validationMap.put("type",
Arrays.asList(Validation.type.EXTERNAL,Validation.type.INTERNAL));
Solution 3:[3]
I believe Your code does not work because Validation.Type is not an instance (of an enum). When you put a value in your map, I believe you would want to put in an actual instance as a value. I suppose that is why the above answers suggest adding an actual instance to the Map such as Type.INTERNAL or using a class instance.
This code will run
Map<String, Object> validationMap = new HashMap<String, Object>();
// this works
validationMap.put("type", Validation.Type.EXTERNAL);
// as shown by:
System.out.println(validationMap.toString());
// here is an analogy:
// make an instance of a class
Validation validation = new Validation();
// this works
validationMap.put("classType",validation);
Validation validationGet = (Validation) validationMap.get("classType");
System.out.println(validationMap.toString());
// by analogy this will not work because Validation is not an instance:
// validationMap.put("classType",Validation);
And the output on my machine is: {type=EXTERNAL}
{type=EXTERNAL, classType=Validation@3feba861}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mark |
| Solution 2 | Nicholas K |
| Solution 3 | David R. |
