I want to create an enum class in java 11 with key value I create a enum like this
JavaScript
x
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
JavaScript
[
"ACTIVE",
"INACTIVE"
]
But i want to got like this
JavaScript
[
{
"Key": "Inactive",
"value":"2"
},
{
"Key": "Active",
"value":"1"
}
]
how can i call my enum tio get a result like this
Advertisement
Answer
There is nothing to prevent you from returning a map entry which contains the key,value
pair.
JavaScript
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.
JavaScript
System.out.println(e);
Prints
JavaScript
Key: = Active
Value: = 1
Active=1
You can also override toString of your Enum and do something like this.
JavaScript
public String toString() {
return String.format(""key": "%s",%n"value": "%s"",
getKey(), getValue());
}
System.out.println(Status.ACTIVE);
Prints
JavaScript
"key": Active",
"value": "1"