Created map in enum using parameters
- Key: AUTQ - Value: AUTP
- Key: FAUQ - Value: FAUP
I created map but now stuck in static and non static calls within enum
AUTHOR("AUTQ","AUTP"), <--- Author is of no use but the values AUTQ is Key and AUTP is value
FINA("FAUQ","FAUP"),
private final Map<String, String> val;
MessageFunction(String key, String value){
this.val = new HashMap<>();
this.val.put(key.toUpperCase(), value); <--- Created a Map
}
public static String getResultValue( String fromValue) {
return this.val.get(fromValue.toUpperCase()); <--- How to access it?
}
When i add static then it do not allow to call this.val (Can not be referred from static context)
When i add non static then not sure how to call it in code.
Could you please suggest how to handle this use case?
CodePudding user response:
You can create the map contents in a static block.
public enum MessageFunction {
AUTHOR("AUTQ", "AUTP"),
FINA("FAUQ", "FAUP");
private static final Map<String, String> val;
static {
val = Arrays.stream(MessageFunction.values())
.collect(Collectors.toMap(my -> my.key.toUpperCase(), my -> my.value));
}
MessageFunction(String key, String value) {
this.key = key;
this.value = value;
}
private final String key;
private final String value;
public static String getResultValue(String fromValue) {
return val.get(fromValue.toUpperCase());
}
}
Both the below calls print AUTP
.
System.out.println(MessageFunction.getResultValue("AUTQ"));
System.out.println(MessageFunction.getResultValue("autq"));