Search code examples
javahashmap

How to implement a hashmap with string as a key and value to it is a function to perform


I need a logic to change the below source such that

if (getString(attributes, NAME_ATTR).equals("Title"))
{
    object.setTitle(getString(attributes, VALUE_ATTR));
}
else if (getString(attributes, NAME_ATTR).equals("Id"))
{
    object.setID(getString(attributes, VALUE_ATTR));
}
else if (getString(attributes, NAME_ATTR).equals("PhoneNumber"))
{
    object.setPhoneNumber(getString(attributes, VALUE_ATTR));
}
else if (*)//lot of cases like this
{
    object.set*(getString(attributes, VALUE_ATTR));
}
...

This needs to be done using a hashMap.

I want to store "Title", "Id", "PhoneNumber", ..etc. as keys in a hashmap and the values should be doing the functionality "object.setTitle(getString(attributes, VALUE_ATTR))".

Keys        |   Values
----------------------------
Title       | object.setTitle(getString(attributes, VALUE_ATTR)) (should set the tilte field in the object)
            |
Id          | object.setId(getString(attributes, VALUE_ATTR)) (should set the id field in the object)
            |
etc..       | should set the specific field in the object  

How can I implement this?


Solution

  • Use a Runnable, or a Callable, or any other interface or abstract class as the value type:

    map.put("Title", new Runnable() {
        @Override
        public void run() {
            object.setTitle(getString(attributes, VALUE_ATTR))
        }
    });
    

    And to use it:

    Runnable r = map.get("Title");
    r.run();
    

    With Java 8 lambdas, the code is much less verbose:

    map.put("Title", () -> object.setTitle(getString(attributes, VALUE_ATTR)));