Let say that we have a method that returns ConcurentMap with pairs <String, String> for old and new values of numbers.
public ConcurrentMap<String, String> getAllOldAndNewPairs() {
return databaseConnector.executeQuery(QUERY, new QueryLauncher<ConcurrentHashMap<String, String>>() {
@Override
public ConcurrentHashMap<String, String> processResult(Results results) throws DAOException {
ConcurrentHashMap<String, String> oldAndNewPairs = new ConcurrentHashMap<>();
while (results.next()) {
oldAndNewPairs.put(results.getString(Column.OLD_NUMBER), results.getString(Column.NEW_NUMBER));
}
return oldAndNewPairs;
}
});
}
I want to fill the guava cache with <Key, Pair> record from method getAllOldAndNewPairs()
So far I have a method like:
public void propagateCache() {
LoadingCache<String, String> loadingCache =
CacheBuilder.newBuilder().build(new CacheLoader<String, String>() {
@Override
public String load(String s) throws Exception {
return getAllOldAndNewPairs();
}
});
}
but currently IDE complaining about line:
return getAllOldAndNewPairs();
Required Type: String - Provided: Concurrent Map<String, String>
I was trying either:
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.build(CacheLoader.from(this::getAllOldAndNewPairs));
and either this did not bring a desirable effect.
I will be grateful for suggestions on how to solve this problem and fill the cache with <Key, Pair> values from method getAllOldAndNewPairs.
Any guava cache implementation can be populated via map. The following method is part of Guava Cache Interface:
void putAll(Map<? extends K, ? extends V> var1);
That being said, you are incorrectly using LoadingCache. When the key is not present in the cache, cache loader provides the logic to determine the value corresponding to the key. Hence the cache loader returns value object (String in your case).