Last active
August 29, 2015 13:57
-
-
Save andresteingress/9697217 to your computer and use it in GitHub Desktop.
Memoizer in JDK 8
This file contains 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
public class Memoizer { | |
public static class MemoizeFunction<T, R> implements Function<T, R> { | |
private final Map<List, R> cache = new HashMap<>(); | |
private final Function<T, R> function; | |
public MemoizeFunction(Function<T, R> function) { | |
Objects.requireNonNull(function); | |
this.function = function; | |
} | |
@Override | |
public R apply(T t) { | |
List key = t == null ? Collections.emptyList() : Arrays.asList(t); | |
return cache.computeIfAbsent(key, list -> function.apply(t)); | |
} | |
} | |
public static <T, R> Function<T, R> memoize(Function<T, R> func) { | |
Objects.requireNonNull(func, "Given function must not be null!"); | |
return new MemoizeFunction<>(func); | |
} | |
} | |
public class MemoizerTest { | |
@Test | |
public void memoize() { | |
Function<Integer, Integer> func = Memoizer.memoize((Integer i) -> i + 1); | |
assertEquals(Integer.valueOf(3), func.apply(2)); | |
assertEquals(Integer.valueOf(3), func.apply(2)); | |
assertEquals(Integer.valueOf(4), func.apply(3)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment