How to get values out of enums stored in a map?
I have multiple enum types in a class. These enum types are stored as values in a map. My requirement is to get values from a particular enum type (name passed as a parameter).
In the following example, Test1 and Test2 are stored in a map. I want to get corresponding values of Y for passed values of x and the enum type (Test1 and Test2..).
public class TestClass {
public enum Test1 {
Const1("x1", "y1"),
Const2("x2", "y2");
private String x;
private String y;
Test1(String x, String y) {
this.x = x;
this.y = y;
}
}
public enum Test2 {
Const1("x1", "y1"),
Const2("x2", "y2");
private String x;
private String y;
Test2(String x, String y) {
this.x = x;
this.y = y;
}
}
public static final Map<String, Collection<? extends Enum<?>>> testMap = Collections.unmodifiableMap(
new HashMap<String, Collection<? extends Enum<?>>>() {
{
put("Test1", Arrays.asList(Test1.values()));
put("Test2", Arrays.asList(Test2.values()));
}
}
);
//get function to be called from outside
public static String getValueY(String x, String enumType) {
return testMap.get(enumType).stream()....
}
public static void main(String[] args) {
getValueY("x1", "Test1"); //This should give value as y1
}
}
question from:
https://stackoverflow.com/questions/65899381/how-to-retrieve-values-from-enums-stored-in-a-map 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…