How to Implement a Cache Eviction Policy using TreeMap in Java? Last Updated : 28 Feb, 2024 Comments Improve Suggest changes Like Article Like Report To enhance application speed, caching is a method that stores frequently visited data in memory. When the cache fills up, a cache eviction policy decides which things must be removed. A sorted map implementation is provided by Java's TreeMap, which may be used to create a cache with a unique eviction strategy. A TreeMap makes efficient retrieval and iteration possible by keeping the keys ordered. Here, we will be using a TreeMap with timestamps as keys to design a cache eviction strategy in which the oldest items are removed first. LFU (Least Frequently Used) Cache Eviction PolicyBelow is the implementation of the LFU (Least Frequently Used) Cache Eviction Policy using TreeMap in Java: Java // Java Program to implement LFU using TreeMap import java.util.*; class LFUCache<K, V> { private final int capacity; // Store actual key-value pairs private final Map<K, V> cache; // Store frequency of each key private final Map<K, Integer> frequencyMap; // TreeMap for efficient frequency tracking private final TreeMap<Integer, LinkedHashSet<K>> frequencyCounter; public LFUCache(int capacity) { this.capacity = capacity; this.cache = new HashMap<>(); this.frequencyMap = new HashMap<>(); this.frequencyCounter = new TreeMap<>(); } public V get(K key) { if (!cache.containsKey(key)) { return null; } // Update frequency int frequency = frequencyMap.get(key); frequencyMap.put(key, frequency + 1); // Update frequencyCounter frequencyCounter.get(frequency).remove(key); if (frequencyCounter.get(frequency).isEmpty()) { frequencyCounter.remove(frequency); } frequencyCounter.computeIfAbsent(frequency + 1, k -> new LinkedHashSet<>()).add(key); return cache.get(key); } public void put(K key, V value) { if (capacity <= 0) { // Capacity is zero or negative, no caching return; } if (cache.size() >= capacity) { // Least frequently used element int lowestFrequency = frequencyCounter.firstKey(); K leastFrequentKey = frequencyCounter.get(lowestFrequency).iterator().next(); // Remove from cache and frequency maps cache.remove(leastFrequentKey); frequencyMap.remove(leastFrequentKey); // Remove from frequencyCounter frequencyCounter.get(lowestFrequency).remove(leastFrequentKey); if (frequencyCounter.get(lowestFrequency).isEmpty()) { frequencyCounter.remove(lowestFrequency); } } // Add the new key-value pair to cache cache.put(key, value); // Update frequency maps frequencyMap.put(key, 1); // Update frequencyCounter frequencyCounter.computeIfAbsent(1, k -> new LinkedHashSet<>()).add(key); } } public class LFUCacheExample { public static void main(String[] args) { LFUCache<Integer, String> lfuCache = new LFUCache<>(3); lfuCache.put(1, "One"); lfuCache.put(2, "Two"); System.out.println("Get 1: " + lfuCache.get(1)); lfuCache.put(3, "Three"); lfuCache.put(4, "Four"); System.out.println("Get 2: " + lfuCache.get(2)); System.out.println("Get 3: " + lfuCache.get(3)); System.out.println("Get 4: " + lfuCache.get(4)); } } OutputGet 1: One Get 2: null Get 3: Three Get 4: Four Explanation of the Program:We have implemented the usage of LFU Cache Eviction policy by adding key-value pairs and retrieving those values for different keys.We have implemented a Map to store the actual key-value pair and the frequency of each key by using frequencyMap.Then we have implemented a TreeMap to track efficient frequency by the use of frequencyCounter.After that, by using put() and get() methods, we have added and retrieved key-value pairs to the cache.Then the LFUCache class creates an object with capacity of 3, then adds and retrieves the values using get() method. Comment More infoAdvertise with us Next Article How to Implement a Cache Eviction Policy using TreeMap in Java? R rahulkatr5460 Follow Improve Article Tags : Java Java Programs java-TreeMap Java Examples Practice Tags : Java Similar Reads Implementation of LRU Cache Using TreeMap in Java In Java, an LRU (Least Recently Used) cache is a data structure that stores a limited number of items and removes the least recently used item when the limit is reached. It is commonly used in computer systems to improve performance by keeping frequently used data readily available, In this article, 5 min read How to Create TreeMap Objects using Comparable Interface in Java? In Java, the TreeMap class is an implementation of the SortedMap interface that stores key-value pairs in a sorted order based on the natural ordering of the keys. By default, the keys are sorted in ascending order. If you want to sort the keys based on a custom ordering criteria, you can use the Co 6 min read Java MultiSet Implementation using TreeMap MultiSet is a generalization of the concept of a set. Its main idea is to allow a member of a multiset to have zero, one, or more than one occurrence in the multiset. In MultiSet, we can delete one occurrence of a member as well as all the occurrences of a member of MultiSet. Java has Set interface 7 min read How to Get TreeMap Key or Value using Index in Java? The TreeMap in Java is used to implement the Map interface and NavigableMap along with the AbstractMap Class. The TreeMap is sorted according to the natural ordering of its keys. The TreeMap class is a Red-Black tree implementation of the Map interface and thus does not expose any methods using whic 5 min read Java Program to Implement TreeMap API The TreeMap is used to implement Map interface and NavigableMap along with the AbstractMap class in java. The map is sorted by the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Now, in implementing TreeMap API, the task is div 6 min read How to Implement a Custom Order or Sorting for Key-Value Pairs in a TreeMap in Java? The Java Collections Framework includes the TreeMap class, in which Java offers a sorted collection of key-value pairs. By default, TreeMap uses a custom Comparator or arranges components according to their natural ordering. In this article, we will learn how to apply a custom order for key-value pa 2 min read How to Create an Immutable TreeMap in Java and it's Benefits? A TreeMap is a component of the Java Collections Framework in Java. A TreeMap is immutable which means it cannot be changed once it has been created. This implies that you are unable to add, delete, or change any items after the TreeMap has been created. In this article, we will learn how to create 2 min read How to Create a TreeMap in Java and Add Key-Value Pairs in it? In Java, a TreeMap maintains elements in a sorted order as it is an implementation of the SortedMap Interface. It stores key-value pairs in a sorted order. In this article, we will explore the creation of TreeMap in Java and learn the step-by-step process of adding key-value pairs. Program to Create 2 min read How to Handle Concurrent Access and Modification of a TreeMap Using Concurrent Collections in Java? To solve data corruption in a multithreaded context, and thread safety, Java offers concurrent collections in the java.util.concurrent package. In this article, we will learn the use of concurrent collections to manage simultaneous access and change of a TreeMap. Concurrent Collections: Java concurr 2 min read How to Convert TreeMap to an ArrayList in Java? TreeMap is a part of the Java Collection framework. Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. It provides an efficient means of storing key-value pairs in sorted order. Java TreeMap contains only unique elements. It cannot 4 min read Like