I have a set of string which I will be using as the Keys and for a particular string I want a function to be called. So is it possible to assign a function to the value in the pair?
exampleMap.get("SOME_STRING"); // should call a function abc();
Encapsulate your function in a Java interface:
public interface Task {
void doSomething();
}
and then pouplate the map with instances of this interface:
map.put("someString", new Task() {
@Override
public void doSomething() {
System.out.println("foo");
}
});
map.put("someOtherString", new Task() {
@Override
public void doSomething() {
System.out.println("bar");
}
});
Then to call the function (task) associated with a given string s:
map.get(s).doSomething();
No, java does not support any method objects yet. You could use reflection or try to replace your strings with enum constants and call the method on them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With