Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maps : In Java Maps can I assign a function to the value in the <K,V> pair? [duplicate]

Tags:

java

hashmap

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();
like image 698
Daanish Avatar asked Oct 25 '25 03:10

Daanish


2 Answers

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();
like image 120
JB Nizet Avatar answered Oct 26 '25 16:10

JB Nizet


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.

like image 44
morpheus05 Avatar answered Oct 26 '25 15:10

morpheus05



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!