有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 1 楼答案

    Java中的映射定义为Map<K,V>,其中K是键的类型,在您的情况下是字符串,V是值的类型,在您的情况下我不知道,所以让我们说对象

    填充地图的最简单方法是使用Map.put(K key, V value)。 从地图中检索项目的方法是V Map.get(K key)

    当有人执行map.get("something")时,您正在请求执行一个函数。但是你需要把函数存储在地图中。这将导致创建自己的映射实现,并使用自定义(且模糊)逻辑来处理它

    我建议您存储该函数,然后用类似的方法执行它:

    import java.util.HashMap;
    import java.util.Map;
    import java.util.function.Function;
    
    public class FunctionMap {
    
        public static void main(String[] args) {
            // Declare the map
            Map<String, Function> functionMap = new HashMap<>();
    
            // Add functions to map
            functionMap.put("toStringWithLambda", object -> object.toString());
            functionMap.put("toStringWithMethodReference", Object::toString);
            functionMap.put("toStringWithCustomMethodReference", FunctionMap::myCustomToString);
            functionMap.put("toStringWithFunctionReturningLambda", FunctionMap.myCustomToString());
    
            // Execute all functions
            functionMap.forEach((key, function) -> function.apply("MyParameter"));
    
            // Execute a single function
            functionMap.get("toStringWithLambda").apply("MyParameter");
        }
    
        private static String myCustomToString (Object object) {
            return "toStringWithCustomMethodReference";
        }
    
        private static Function<Object, String> myCustomToString() {
            return o -> "toStringWithFunctionReturningLambda";
        }
    }