简体   繁体   English

Java 选择基于 hashmap 密钥的方法

[英]Java pick a method base on a hashmap key

I have a question regarding optimizing my program in java.我有一个关于在 java 中优化我的程序的问题。 Right now I have a working hashmap and I want to find a way to pick a method based on the maps key.现在我有一个工作 hashmap 并且我想找到一种方法来选择基于 maps 键的方法。 Essentially I have a class that contains the map and I have a class for each possible key.本质上,我有一个包含 map 的 class ,并且每个可能的键都有一个 class 。 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.我只是要为每个可能的键创建一个 if 语句,如果 map 包含它,我会将键及其值发送到特定的 class 以执行一些代码。 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.这会起作用,但感觉像是不好的做法,我的目标是在 java 中使用更好的做法,所以我想知道在没有 if 语句的 janky 集群的情况下执行此操作的最佳方法是什么。

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.我不确定如何 go 关于这个也许我可以从主要的 class 扩展所有类并使用某种形式的方法重载但我认为只有在我遍历映射值并将它们的键用作参数超载。

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.除了循环之外,我的另一个想法是将 map 发送到所有类,如果它们包含密钥,如果不执行任何操作,则通过它。

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

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

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