Skip to content

Instantly share code, notes, and snippets.

@benwaffle
Last active August 29, 2015 14:12
Show Gist options
  • Save benwaffle/f60dcb94cf18bb7d41d1 to your computer and use it in GitHub Desktop.
Save benwaffle/f60dcb94cf18bb7d41d1 to your computer and use it in GitHub Desktop.
memoize a java function
import java.util.*;
import java.util.function.Function;
public class Memoize {
static interface F<T,R> extends Function<T,R> {}
// not thread safe
static <T,R> F<T, R> memoize(F<T, R> f) {
Map<T, R> cache = new HashMap<>();
return (x) -> {
cache.putIfAbsent(x, f.apply(x));
return cache.get(x);
};
}
static int longComputation(int x) {
try { Thread.sleep(1000); } catch (Exception e) {}
return x;
}
public static void main(String[] args) {
F<Integer, Integer> f = memoize(Memoize::longComputation);
System.out.println(f.apply(3));
System.out.println(f.apply(3));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment