How to use enum key value in java

Tags: ,



I want to create an enum class in java 11 with key value I create a enum like this

public enum status{

    ACTIVE("Active", 1), IN_ACTIVE("In Active", 2);

    private final String key;
    private final Integer value;

    Status(String key, Integer value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }
    public Integer getValue() {
        return value;
    }
}

the problem that when i do Saison saison.getvalues() i got like this

[
"ACTIVE",
"INACTIVE"
]

But i want to got like this

[
{
"Key": "Inactive", 
"value":"2"
},
{
"Key": "Active",
 "value":"1"
}
]

how can i call my enum tio get a result like this

Answer

There is nothing to prevent you from returning a map entry which contains the key,value pair.

 enum Status {

    ACTIVE("Active", 1), IN_ACTIVE("In Active", 2);

    private final String key;
    private final int value;

    Status(String key, int value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }
    public int getValue() {
        return value;
    }
    public Entry<String,Integer> getBoth() {
        return new AbstractMap.SimpleEntry<>(key, value);
    }   
}

Entry<String,Integer> e = Status.ACTIVE.getBoth();
System.out.println("Key: = " + e.getKey());
System.out.println("Value: = " + e.getValue());

or print the toString() value of the Entry.

System.out.println(e);
    

Prints

Key: = Active
Value: = 1
Active=1

You can also override toString of your Enum and do something like this.

public String toString() {
    return String.format(""key": "%s",%n"value": "%s"",
            getKey(), getValue());
}

System.out.println(Status.ACTIVE);

Prints

"key": Active",
"value": "1"

    


Source: stackoverflow