Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

LRU Cache java

class LRUCache {

    LinkedHashMap<Integer,Integer> data = new LinkedHashMap<Integer,Integer>();
    int capacity =0;
    int value = -1;
    
    public LRUCache(int capacity) {
        this.capacity = capacity;
    }
    
    public int get(int key) {
        
        if(data.containsKey(key)){
            value = data.get(key);
            data.remove(key);
            data.put(key,value);
        }else{
            value = -1;
        }
        return value;
    }
    
    public void put(int key, int value) {
        if(!data.containsKey(key)){
            
            if(data.size() >= capacity ){
                
                for(Map.Entry first : data.entrySet()){
                    data.remove(first.getKey());
                    break;
                }
                
            }
            
            data.put(key,value);
            
        }else{
            data.remove(key);
            data.put(key,value);
        }
    }
}
 
PREVIOUS NEXT
Tagged: #LRU #Cache #java
ADD COMMENT
Topic
Name
5+6 =