Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most practical way to have "functions in a dictionary" in Java?

When programming with C/C++ or Python I sometimes used to have a dictionary with references to functions according to the specified keys. However, I don't really know how to have the same -- or at the very least similar -- behavior in Java allowing me dynamic key-function (or method, in Java slang) association.

Also, I did find the HashMap technique somebody suggested, but is that seriously the best and most elegant way? I mean, it seems like a lot to create a new class for every method I want to use.

I'd really appreciate every input on this.

like image 598
Marc Müller Avatar asked Dec 22 '22 10:12

Marc Müller


1 Answers

You don't need to create a full, name class for each action. You can use anonymous inner classes:

public interface Action<T>
{
    void execute(T item);
}

private static Map<String, Action<Foo>> getActions()
{
    Action<Foo> firstAction = new Action<Foo>() {
        @Override public void execute(Foo item) {
             // Insert implementation here
        }
    };
    Action<Foo> secondAction = new Action<Foo>() {
        @Override public void execute(Foo item) {
             // Insert implementation here
        }
    };
    Action<Foo> thirdAction = new Action<Foo>() {
        @Override public void execute(Foo item) {
             // Insert implementation here
        }
    };
    Map<String, Action<Foo>> actions = new HashMap<String, Action<Foo>>();
    actions.put("first", firstAction);
    actions.put("second", secondAction);
    actions.put("third", thirdAction);
    return actions;
}

(Then store it in a static variable.)

Okay, so it's not nearly as convenient as a lambda expression, but it's not too bad.

like image 180
Jon Skeet Avatar answered Mar 05 '23 13:03

Jon Skeet