I came across an interesting problem and was wondering if and how could this be done in Java: Create a method which can memoize any function/method . The method has the following arguments : the method/function and the argument(s) for it.
For example let's say i have this method :
int addOne(int a) { return a + 1;}
and i call my memoization method two times with the same arguments : addOne and 5 for example, the first call should actually call the addOne method and return the result and also store that result for that given argument. The second time when i call it should know this has been called before and just look up the previous answer.
My idea would be to have something like a HashMap<Callable,HashMap<List<Objects>,Object>>
where you would store the previous answers and look them up later on.I think this can be somehow done with lambda expressions but i'm not that familiar with them.I'm not quite sure how to write this method and would appreciate some help.
Can this be done with this approach?
In Java 8 you can do it like that:
This is a good tutorial. There it is made for any method.
From the tutorial:
The Memoizer class:
How to use the class:
Output:
You can memoize any function with Java 8's
MethodHandle
s and lambdas if you're willing to give up type safety on the parameters:Working Example
This creates a variable-arity lambda that encloses the function and is almost as fast as calling the function directly (i.e., no reflection happens inside of
call(Object...args)
) after the lambda is constructed since we're usingMethodHandle.invoke()
instead ofMethod.invoke()
.You can still do this without lambdas (replace with anonymous classes) and MethodHandles (replace with Method.invoke), but there will be performance penalties that make this less attractive for performance-conscious code.