java – 从HashMap中删除最旧的对象以达到一定的大小?

前端之家收集整理的这篇文章主要介绍了java – 从HashMap中删除最旧的对象以达到一定的大小?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 Java中的哈希映射,我需要限制其大小(50000的顺序).但我应该只删除最旧的项目.项的时间戳存储在条目对象的字段中:
Map<String,MyModel> snapshot = new  HashMap<>();

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

我还按时间戳顺序将它们插入到地图中.

完成这种删除最旧条目的最有效方法是什么?请注意,时间“阈值”未知,只有Map的最终大小.

解决方法

HashMap没有“最老的”,它没有“第一”,它没有订单.

另一方面,LinkedHashMap就是为此设计的,它在条目之间维护一个双向链表,因此保持它们的插入顺序,它还提供了一个removeEldestEntry方法

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");
}

输出

{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}

大健康警告

Note that this implementation is not synchronized. If multiple threads access a linked hash map concurrently,and at least one of the threads modifies the map structurally,it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists,the map should be “wrapped” using the Collections.synchronizedMap method. This is best done at creation time,to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new LinkedHashMap(...));

LinkedHashMap JavaDoc

原文链接:https://www.f2er.com/java/127798.html

猜你在找的Java相关文章