fr.vergne.pester.util.cache.Cache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pester-core Show documentation
Show all versions of pester-core Show documentation
Implementation of the Pester library.
The newest version!
package fr.vergne.pester.util.cache;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
public interface Cache {
T get(Key key);
T get(Key key, Supplier supplier);
public static Cache create() {
Map, Object> map = new HashMap<>();
return new Cache() {
@Override
public T get(Key key) {
return get(key, () -> {throw new IllegalStateException("No value stored for " + key);});
}
@Override
public T get(Key key, Supplier supplier) {
return key.cast(map.computeIfAbsent(key, k -> supplier.get()));
}
};
}
public static Function onFunction(Function function) {
Cache cache = create();
return value -> cache.get(ParameteredKey.create(value), () -> function.apply(value));
}
public static Supplier onSupplier(Supplier supplier) {
Cache cache = create();
Key key = ParameteredKey.create(new Object());
return () -> cache.get(key, supplier);
}
}