ConcurrentMapBasedToIntFunctionMemoizer extends ConcurrentMapBasedMemoizer<KEY, Integer> implements ToIntFunction<INPUT> { @Override public int applyAsInt(final INPUT input) { final KEY key = keyFunction.apply(input); return computeIfAbsent(key, givenKey -> Integer.valueOf(function.applyAsInt(input))) .intValue(); } @SuppressWarnings(CompilerWarnings.NLS)  ConcurrentMapBasedToIntFunctionMemoizer(
            final ConcurrentMap<KEY, Integer> cache,
            final Function<INPUT, KEY> keyFunction,
            final ToIntFunction<INPUT> function); @Override int applyAsInt(final INPUT input);  }
@Test public void shouldMemoizeFunction() { final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final ToIntFunction<String> function = input -> 123; final Function<String, String> keyFunction = Function.identity(); final ConcurrentMapBasedToIntFunctionMemoizer<String, String> memoizer = new ConcurrentMapBasedToIntFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsInt("123"); }
@Test public void shouldUseSetCacheKeyAndValue() { final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final ToIntFunction<String> function = input -> 123; final Function<String, String> keyFunction = Function.identity(); final ConcurrentMapBasedToIntFunctionMemoizer<String, String> memoizer = new ConcurrentMapBasedToIntFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsInt("123"); Assert.assertFalse("Cache is still empty after memoization", memoizer.viewCacheForTest().isEmpty()); Assert.assertEquals("Memoization key does not match expectations", "123", memoizer.viewCacheForTest().keySet().iterator().next()); Assert.assertEquals("Memoization value does not match expectations", 123, memoizer.viewCacheForTest().values().iterator().next().intValue()); }
@Test @SuppressWarnings(CompilerWarnings.UNCHECKED) public void shouldUseCallWrappedFunction() { final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final ToIntFunction<String> function = Mockito.mock(ToIntFunction.class); final Function<String, String> keyFunction = Function.identity(); final ConcurrentMapBasedToIntFunctionMemoizer<String, String> memoizer = new ConcurrentMapBasedToIntFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsInt("123"); Mockito.verify(function).applyAsInt("123"); }
@Test public void shouldUseReturnFunctionResult() { final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final ToIntFunction<String> function = input -> 123; final Function<String, String> keyFunction = Function.identity(); final ConcurrentMapBasedToIntFunctionMemoizer<String, String> memoizer = new ConcurrentMapBasedToIntFunctionMemoizer<>( cache, keyFunction, function); Assert.assertEquals(123, memoizer.applyAsInt("123")); }