Learn-dsa..in 30 days!



























CC-13 : Create a simple LRU cache POC.

Description:

LRU cache stands for Least Recently Used cache. Based on space available in the cache, the items which are accessed recently will be cached, the items which have not been recently accessed will be removed from the cache. Create a simple POC for a LRU cache.

Test cases and expected outputs:

Input Parameters Expected outputs
LinkedHashSet lru=new LinkedHashSet(); Lrusize=5; (this is max capacity of acche) lru.put(5); The cache contents: 5
lru.put(11); The cache contents: 5 11
lru.put(9); The cache contents: 5 11 9
lru.put(7); The cache contents: 5 11 9 7
lru.put(4); The cache contents: 5 11 9 7 4
lru.put(3); The cache contents: 11 9 7 4 3
lru.put(8); The cache contents: 9 7 4 3 8
lru.put(3); The cache contents: 9 7 8 3 4

Pseudocode:

Create a java class called SetSimpleLRUCache.
In SetSimpleLRUCache initialize a member variable lru of type LinkedHashSet. Note that a LinkedHashSet preserves the order in which elements are added to it.
Initialize another integer member variable lruSize=5. This represents the maximum capacity of the lru cache.
Create a method put() that takes tocache as input:
If lru already contains tocache, remove tocache from its current position in lru and add it again to make it most recently accessed.
Else If current size of lru is 5, it means the cache is full and we need to remove the oldest element from lru and then add tocache to lru.
Else if none of above conditions match, then add tocache to lru.
Create a method getMostRecent() :
The method returns the most recently added element from lru using getLast() method.
Create a method getOldest() :
The method returns the oldest added element from lru using getFirst() method.
Create a method printCacheContents() that iterates through lru and prints the contents of the cache. Since we have used a LinkedHashSet, the order in which items are added to lru are preserved while printing the cache contents.

Code:

public class SetSimpleLRUCache {
LinkedHashSet<Integer> lru=new LinkedHashSet<Integer>();
int lruSize=5;
	
public void put(int tocache) {
	if (lru.contains(tocache)) {
		lru.remove(tocache);
		lru.add(tocache);			
	}else if (lru.size()==5) {
		lru.remove(lru.getFirst());
		lru.add(tocache);
	}else {
		lru.add(tocache);
	}	
}
	
public int check(int fromcache) {
	if (lru.contains(fromcache)) {
		return fromcache;
	}else {
		return -1;
	}
}

public int getMostRecent() {
	return lru.getLast();
}

public int getOldest() {
	return lru.getFirst();
}


	
public void printCacheContents(){
	Iterator itr=lru.iterator();
	System.out.print("\nThe cache  contents: ");
	while (itr.hasNext()) {
		System.out.print(itr.next()+ " ");
	}	
	System.out.println("\n");
}
	
}

Click here to download and run code and test cases !