Junior
What is the simplest way to implement caching?
sobes.tech AI
Answer from AI
In-memory caching using Map.
import java.util.HashMap;
import java.util.Map;
public class SimpleCache<K, V> {
private final Map<K, V> cache = new HashMap<>();
public V get(K key) {
return cache.get(key); // Get value by key
}
public void put(K key, V value) {
cache.put(key, value); // Add or update value in cache
}
public void remove(K key) {
cache.remove(key); // Remove key from cache
}
public void clear() {
cache.clear(); // Clear entire cache
}
}
This approach is the simplest but has limitations in memory volume and does not support eviction of old elements (TTL/LRU). For more advanced scenarios, libraries like Guava Cache, Ehcache, or Caffeine are used.