如何在Java中使用枚举键值

问题描述

我想在Java 11中使用键值创建一个枚举类 我创建了这样的枚举

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;
    }
}

当我进行Saison saison.getvalues()时出现的问题 我就这样

[
"ACTIVE","INACTIVE"
]

但是我想要这样

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

我怎么称呼我的枚举得到这样的结果

解决方法

没有什么可以阻止您返回包含key,value对的地图条目。

 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());

或打印Entry的toString()值。

System.out.println(e);
    

打印

Key: = Active
Value: = 1
Active=1

您还可以覆盖Enum的toString并执行类似的操作。

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

System.out.println(Status.ACTIVE);

打印

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