Skip to content

Instantly share code, notes, and snippets.

@efekos
Created September 19, 2024 21:11
Show Gist options
  • Save efekos/32476a6cc426b48c3c18db19c6a8e28d to your computer and use it in GitHub Desktop.
Save efekos/32476a6cc426b48c3c18db19c6a8e28d to your computer and use it in GitHub Desktop.
A small class to cache the result of a function.
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
public class CachedFunction<T, R> {
private final Function<T, R> func;
private final Map<Integer, R> cache = new HashMap<>();
public CachedFunction(Function<T, R> func) {
this.func = func;
}
public R apply(T t) {
int i = t.hashCode();
if (cache.containsKey(i)) return cache.get(i);
R r = func.apply(t);
cache.put(i, r);
return r;
}
public void clear() {
cache.clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment