import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UrlCache {
private final Map<String, List<String>> cache = new HashMap<>(); // Cache to store URL lists
private final int cacheSizeLimit;
public UrlCache(int cacheSizeLimit) {
this.cacheSizeLimit = cacheSizeLimit;
}
/**
* Retrieves a list of URLs for a given environment.
*
* @param environment The environment (e.g., "staging").
* @return A list of URLs, or null if not found in the cache.
*/
public List<String> getUrls(String environment) {
if (!cache.containsKey(environment)) {
return null; // Not in cache
}
return cache.get(environment);
}
/**
* Adds a list of URLs to the cache for a given environment.
*
* @param environment The environment (e.g., "staging").
* @param urls The list of URLs to cache.
*/
public void setUrls(String environment, List<String> urls) {
if (cache.size() >= cacheSizeLimit) {
// Remove the least recently used entry (simplistic eviction)
String firstKey = cache.keySet().iterator().next();
cache.remove(firstKey);
}
cache.put(environment, urls);
}
public static void main(String[] args) {
UrlCache cache = new UrlCache(2); // Cache size limit of 2
List<String> stagingUrls1 = List.of("https://staging.example.com/page1", "https://staging.example.com/page2");
cache.setUrls("staging", stagingUrls1);
List<String> stagingUrls2 = List.of("https://staging.example.com/page3", "https://staging.example.com/page4");
cache.setUrls("staging", stagingUrls2); // This will evict one of the old URLs
List<String> retrievedUrls = cache.getUrls("staging");
System.out.println(retrievedUrls); // Output: [https://staging.example.com/page3, https://staging.example.com/page4] or similar order
List<String> stagingUrls3 = cache.getUrls("staging");
System.out.println(stagingUrls3); //Output: [https://staging.example.com/page3, https://staging.example.com/page4] or similar order
}
}
Add your comment