I ran into an interesting problem and wondered how and how to do this in Java: Create a method that can memoize any function / method. A method has the following arguments: a method / function and an argument for it.
For example, let's say I have this method:
int addOne(int a) { return a + 1;}
and I call the memoization method twice with the same arguments: for example, addOne and 5, the first call should actually call the addOne method and return the result, and also save this result for the given argument. The second time I call this, I should know that it was called earlier and just looked at the previous answer.
My idea would be to have something like HashMap<Callable,HashMap<List<Objects>,Object>>where you would save the previous answers and look at them later. I think this can be somehow done with lambda expressions, but I am not familiar with them. "Not quite sure how to write this method, and would appreciate help."
Can this be done with this approach?
source
share