Search code examples
lambdafunctional-programmingjava-8function-pointersfunctional-interface

java 8 - declare method to use in map, and pass the value to the method later on


I want to be able to declare methods in map to use up-front BUT, specify the parameter to pass to the function NOT when declaring the map and implementing the FunctionalInterface, but rather when using it.

Example - There's the method DateTime.now().minusMinutes(int minutes). I want to put this method in map and call it based on some string key, BUT I want to specify the int minutes to pass to the method when using it. is that possible?

If possible, I would think it would look something like this:

@FunctionalInterface
interface TimeFrame {
    DateTime createTimeFrame(int value);
}

private Map<String, TimeFrame> map = new HashMap<String, TimeFrame>() {{
        map.put("minutes", () -> DateTime.now().minusMinutes());
}}

and to use it, ideally, I want to pass the 4 to the minusMinutes() method

DateTime date = map.get("minutes").createTimeFrame(4);

Off course this is not compiling, but the idea is to declare the method up-front without the parameter, and pass the parameter to minusMinutes() later.

Can this be done?


Solution

  • It seems what you are missing is adding the int parameter to the lambda expression :

    @FunctionalInterface
    interface TimeFrame {
        DateTime createTimeFrame(int value);
    }
    
    ...
    
    map.put("minutes", i -> DateTime.now().minusMinutes(i));
    

    Now

    DateTime date = map.get("minutes").createTimeFrame(4);
    

    should work.