Created
September 19, 2024 21:11
-
-
Save efekos/32476a6cc426b48c3c18db19c6a8e28d to your computer and use it in GitHub Desktop.
A small class to cache the result of a function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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