加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 03:16:24 所属栏目:Java 来源:网络整理
导读:我有一个 Java中的哈希映射,我需要限制其大小(50000的顺序).但我应该只删除最旧的项目.项的时间戳存储在条目对象的字段中: MapString,MyModel snapshot = new HashMap(); 和 public class MyModel { private ZonedDateTime createdAt; // other fields...}
我有一个 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读