简体   繁体   中英

Java pick a method base on a hashmap key

I have a question regarding optimizing my program in java. Right now I have a working hashmap and I want to find a way to pick a method based on the maps key. Essentially I have a class that contains the map and I have a class for each possible key. I was just going to make an if statement for each possible key and if the map contains it I would then send the key with its value to that specific class to execute some code. This would work but it feels like bad practice and my goal is to use better practices in java so I want to know whats the best way to do this without the janky cluster of if statements.

I am not exactly sure how to go about this maybe I could extend all the classes from that main class and use some form of method overloading but I think that would only work If I looped through the maps values and used their key as a parameter to overload.

Another idea I had other than looping was to send the map to all the classes and if they contain the key pass it through if not do nothing.

Something along these lines may work for you:

enum SampleClass {
    CLASS1, CLASS2, CLASS3
}
Map<SampleClass, Supplier<Boolean>> map = new HashMap<>();
map.put(CLASS1, () -> Class1.method("value1"));
map.put(CLASS2, () -> Class2.method("value2"));
map.put(CLASS3, () -> Class3.method("value3"));

boolean result = map.get(CLASS1).get();
class Class1 {
    public static boolean method(String value) {
        // ...
    }
}
// ... and so on for every class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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