A Map in Java is defined as Map<K,V>
, where K is the type of the key, in you case String, and V is the type of the value, in your case I don't know so lets say Object.
The simplest way to populate a map is using Map.put(K key, V value)
.
The way to retrieve a item from a map is V Map.get(K key)
You are asking to execute a function when someone does map.get("something")
. But you need to store the function inside the map. That will lead to create you own map implementation with a custom (and obscure) logic to handle it.
What I would recommend you is to store the function and then execute it with something similar to this:
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";
}
}