Implementing a Least-Recently-Used (LRU) Cache : LinkedHashMap « Collections Data Structure « Java

Implementing a Least-Recently-Used (LRU) Cache

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
  public static void main(String[] argv) throws Exception {
    final int MAX_ENTRIES = 100;
    Map cache = new LinkedHashMap(MAX_ENTRIES + 1, .75F, true) {
      public boolean removeEldestEntry(Map.Entry eldest) {
        return size() > MAX_ENTRIES;

    Object key = "key";
    Object value = "value";
    cache.put(key, value);
    Object o = cache.get(key);
    if (o == null && !cache.containsKey(key)) {
    cache = (Map) Collections.synchronizedMap(cache);


Related examples in the same category

1.Check if a particular key exists in Java LinkedHashMap example
2.Check if a particular value exists in Java LinkedHashMap example
3.Get Set view of Keys from Java LinkedHashMap
4.Get Size of Java LinkedHashMap
5.Iterate through the values of Java LinkedHashMap
6.Remove all values from Java LinkedHashMap
7.Remove value from Java LinkedHashMap
8.Simple Java LinkedHashMap
9.Check if a particular element exists in Java LinkedHashSet
10.Copy all elements of Java LinkedHashSet to an Object Array