Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

java - How to retrieve values from Enums stored in a map?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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<String, Collection<Foo>> testMap 

which then allows you to call both methods, getX() and getY().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...