简体   繁体   English

如何从存储在 map 中的枚举中检索值?

[英]How to retrieve values from Enums stored in a map?

How to get values out of enums stored in a map?如何从存储在 map 中的枚举中获取值?

I have multiple enum types in a class.我在 class 中有多种枚举类型。 These enum types are stored as values in a map.这些枚举类型作为值存储在 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.在以下示例中,Test1 和 Test2 存储在 map 中。 I want to get corresponding values of Y for passed values of x and the enum type (Test1 and Test2..).我想为传递的 x 值和枚举类型(Test1 和 Test2 ..)获取相应的 Y 值。

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

A type-safe way to do this, without reflection:一种类型安全的方法,无需反射:

Declare an interface:声明一个接口:

interface Foo {
  String getX();
  String getY();

Have all your enums implement that interface:所有枚举实现该接口:

public enum Test1 implements Foo { ...

Now you can change your map to现在您可以将 map 更改为

Map<String, Collection<Foo>> testMap 

which then allows you to call both methods, getX() and getY() .然后,您可以调用这两种方法, getX()getY()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM