What is the most practical way to have “functions in a dictionary” in Java?

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

Also, I found a HashMap technique that someone suggested, but is this the best and most elegant way? I mean, for every method I want to use, there seems to be a lot to create a new class.

I would really appreciate every contribution to this.

+4
source share
2 answers

You do not need to create a complete class of names 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 save it in a static variable.)

Good, so it's not as convenient as a lambda expression, but it's not so bad.

+10
source

Short answer: you need to wrap each method in a class called a functor.

+1
source

All Articles