Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Enum | Created map in constructor | But cannot access/send its value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading