Skip to content

Instantly share code, notes, and snippets.

@AlexAvlonitis
Created February 3, 2022 16:45
Show Gist options
  • Save AlexAvlonitis/6c17275d13c90b40dd1093918c7afd93 to your computer and use it in GitHub Desktop.
Save AlexAvlonitis/6c17275d13c90b40dd1093918c7afd93 to your computer and use it in GitHub Desktop.
LRU cache in java
// Lru cache in java with custom doubly linked list.
import java.util.HashSet;
import java.util.Iterator;
public class LRURunner {
public static void main(String[] args) {
Lru lru = new Lru(3);
lru.get("1");
lru.get("2");
lru.get("3");
lru.get("4");
lru.showList();
}
}
public class Lru {
private LinkedList linkedList;
private java.util.HashSet<String> lruHashSet;
private int lruCapacity;
public Lru(int capacity) {
lruCapacity = capacity;
lruHashSet = new HashSet<>();
linkedList = new LinkedList();
}
public void showList() {
linkedList.showList();
}
public void get(String value) {
if (!lruHashSet.contains(value)) {
if(lruCapacity == lruHashSet.size()){
linkedList.popTail();
lruHashSet.remove(value);
}
} else {
linkedList.removeNode(value);
}
linkedList.enqueue(value);
lruHashSet.add(value);
}
}
public class LinkedList {
private Node head;
private Node tail;
public LinkedList() {
head = null;
tail = null;
}
public void showList() {
Node tmpNode = head;
while (tmpNode != null) {
System.out.println(tmpNode.getValue());
tmpNode = tmpNode.getNextNode();
}
}
public void popTail() {
Node prevNode = tail.getPreviousNode();
prevNode.setNextNode(null);
tail = prevNode;
}
public void removeNode(String value) {
Node tmpNode = head;
while (tmpNode != null) {
if (tmpNode.equals(value)) {
Node prevNode = tmpNode.getPreviousNode();
Node nextNode = tmpNode.getNextNode();
prevNode.setNextNode(nextNode);
nextNode.setPreviousNode(prevNode);
}
tmpNode = tmpNode.getNextNode();
}
}
public void enqueue(String value) {
Node node = new Node(value);
if (head == null) {
head = node;
tail = node;
} else {
Node prevHead = head;
head = node;
head.setNextNode(prevHead);
prevHead.setPreviousNode(head);
}
}
}
public class Node {
private String value;
private Node next;
private Node previous;
public Node(String v) {
value = v;
next = null;
previous = null;
}
public Node getNextNode() {
return next;
}
public Node getPreviousNode() {
return previous;
}
public String getValue() {
return value;
}
public void setNextNode(Node node) {
next = node;
}
public void setPreviousNode(Node node) {
previous = node;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment