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

3.2k views Asked by At

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?

2

There are 2 answers

4
Eran On BEST ANSWER

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.

0
Sam On

You simply need to define your lambda function a little differently.

map.put("minutes", (mins) -> DateTime.now().minusMinutes(mins))

mins is an argument that corresponds to the value in your functional interface. You can call it whatever you want; mins is just a suggestion.