0

I am completely new to java and I want to know how to create HashMap with one argument as primitive and second argument as a function call.

HashMap<PrimitiveType,MethodInvocation> map = new HashMap<>();

  • What should I have to declare for MethodInvocation for the HashMap declaration?
  • So that when I call map.get(something) it should result in a function call.
Deep Dalsania
  • 375
  • 3
  • 8
  • 22

1 Answers1

2

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";
    }
}
Ezequiel
  • 3,477
  • 1
  • 20
  • 28