Search code examples
javadictionaryfunctional-programmingfirst-class-functions

How to put method in map?


I have Strings where I need to find brackets (), {}, [] and using stack to check correctness and if there is a mistake to print the position of mistake . So i split them into char array and then want to check symbol by symbol and if its match my map execute my method of pushing/popping to/from the stack.

I imagine it like this:

ParentStack s = new ParentStack();
Map<Character, Method> map = new HashMap<Character, Method>();
map.put('(', s.push('('));
map.put(')', s.pop()); //then check if its opposite 

So is there something like this? Or I have to use switches?


Solution

  • You are calling the method instead of putting it into the map. What you could do instead is to put an instance of the Runnable interface into the map. Runnable is Javas default interface for any method that has no parameter list and no return value. If you need parameters or a return value, you might want to have a look at the interfaces in the package java.util.function. For example Supplier<T> has a return value and Consumer<T> has one parameter.

    Here is an example using Java 8 lambda expressions:

    ParentStack s = new ParentStack();
    Map<Character, Runnable> map = new HashMap<Character, Runnable>();
    map.put('(', () -> s.push('('));
    map.put(')', () -> s.pop());
    

    And the usage:

    map.get('(').run();
    

    The run() method is declared by the Runnable interface and will call the method that you put into the map. Don't be confused by the different names.