Reputation: 5198
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?
Upvotes: 3
Views: 3324
Reputation: 393831
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.
Upvotes: 2
Reputation: 9944
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.
Upvotes: 2