Java – delete the oldest object from the HashMap to reach a certain size?

I have a hash map in Java, and I need to limit its size (in the order of 50000) But I should only delete the oldest items The timestamp of the item is stored in the field of the entry object:

Map<String,MyModel> snapshot = new  HashMap<>();

and

public class MyModel { 
    private zoneddatetime createdAt;
    // other fields...
}

I also insert them into the map in timestamp order

What is the most effective way to complete this deletion of the oldest entries? Please note that the time "threshold" is unknown, only the final size of the map

Solution

HashMap has no "oldest", it has no "first", it has no orders

On the other hand, LinkedHashMap is designed for this purpose. It maintains a two-way linked list between items, so it maintains their insertion order. It also provides a removeeldestentry method:

public static void main(final String args[]) throws Exception {
    final int maxSize = 4;
    final LinkedHashMap<String,String> cache = new LinkedHashMap<String,String>() {
        @Override
        protected boolean removeEldestEntry(final Map.Entry eldest) {
            return size() > maxSize;
        }
    };

    cache.put("A","A");
    System.out.println(cache);
    cache.put("B","A");
    System.out.println(cache);
    cache.put("C","A");
    System.out.println(cache);
    cache.put("D","A");
    System.out.println(cache);
    cache.put("E","A");
    System.out.println(cache);
    cache.put("F","A");
    System.out.println(cache);
    cache.put("G","A");
}

Output:

{A=A}
{A=A,B=A}
{A=A,B=A,C=A}
{A=A,C=A,D=A}
{B=A,D=A,E=A}
{C=A,E=A,F=A}

Big health warning

LinkedHashMap JavaDoc

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>