1. import java.util.HashMap;
  2. import java.util.List;
  3. import java.util.Map;
  4. public class UrlCache {
  5. private final Map<String, List<String>> cache = new HashMap<>(); // Cache to store URL lists
  6. private final int cacheSizeLimit;
  7. public UrlCache(int cacheSizeLimit) {
  8. this.cacheSizeLimit = cacheSizeLimit;
  9. }
  10. /**
  11. * Retrieves a list of URLs for a given environment.
  12. *
  13. * @param environment The environment (e.g., "staging").
  14. * @return A list of URLs, or null if not found in the cache.
  15. */
  16. public List<String> getUrls(String environment) {
  17. if (!cache.containsKey(environment)) {
  18. return null; // Not in cache
  19. }
  20. return cache.get(environment);
  21. }
  22. /**
  23. * Adds a list of URLs to the cache for a given environment.
  24. *
  25. * @param environment The environment (e.g., "staging").
  26. * @param urls The list of URLs to cache.
  27. */
  28. public void setUrls(String environment, List<String> urls) {
  29. if (cache.size() >= cacheSizeLimit) {
  30. // Remove the least recently used entry (simplistic eviction)
  31. String firstKey = cache.keySet().iterator().next();
  32. cache.remove(firstKey);
  33. }
  34. cache.put(environment, urls);
  35. }
  36. public static void main(String[] args) {
  37. UrlCache cache = new UrlCache(2); // Cache size limit of 2
  38. List<String> stagingUrls1 = List.of("https://staging.example.com/page1", "https://staging.example.com/page2");
  39. cache.setUrls("staging", stagingUrls1);
  40. List<String> stagingUrls2 = List.of("https://staging.example.com/page3", "https://staging.example.com/page4");
  41. cache.setUrls("staging", stagingUrls2); // This will evict one of the old URLs
  42. List<String> retrievedUrls = cache.getUrls("staging");
  43. System.out.println(retrievedUrls); // Output: [https://staging.example.com/page3, https://staging.example.com/page4] or similar order
  44. List<String> stagingUrls3 = cache.getUrls("staging");
  45. System.out.println(stagingUrls3); //Output: [https://staging.example.com/page3, https://staging.example.com/page4] or similar order
  46. }
  47. }

Add your comment