Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is a data structure kind of like a hash table, but infrequently-used keys are deleted?
    primarykey
    data
    text
    <p>I am looking for a data structure that operates similar to a hash table, but where the table has a size limit. When the number of items in the hash reaches the size limit, a culling function should be called to get rid of the least-retrieved key/value pairs in the table.</p> <p>Here's some pseudocode of what I'm working on:</p> <pre><code>class MyClass { private Map&lt;Integer, Integer&gt; cache = new HashMap&lt;Integer, Integer&gt;(); public int myFunc(int n) { if(cache.containsKey(n)) return cache.get(n); int next = . . . ; //some complicated math. guaranteed next != n. int ret = 1 + myFunc(next); cache.put(n, ret); return ret; } } </code></pre> <p>What happens is that there are some values of <code>n</code> for which <code>myFunc()</code> will be called lots of times, but many other values of <code>n</code> which will only be computed once. So the cache could fill up with millions of values that are never needed again. I'd like to have a way for the cache to automatically remove elements that are not frequently retrieved.</p> <p>This feels like a problem that must be solved already, but I'm not sure what the data structure is that I would use to do it efficiently. Can anyone point me in the right direction?</p> <hr> <p><strong>Update</strong> I knew this had to be an already-solved problem. It's called an LRU Cache and is easy to make by extending the LinkedHashMap class. Here is the code that incorporates the solution:</p> <pre><code>class MyClass { private final static int SIZE_LIMIT = 1000; private Map&lt;Integer, Integer&gt; cache = new LinkedHashMap&lt;Integer, Integer&gt;(16, 0.75f, true) { protected boolean removeEldestEntry(Map.Entry&lt;Integer, Integer&gt; eldest) { return size() &gt; SIZE_LIMIT; } }; public int myFunc(int n) { if(cache.containsKey(n)) return cache.get(n); int next = . . . ; //some complicated math. guaranteed next != n. int ret = 1 + myFunc(next); cache.put(n, ret); return ret; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload