gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:06:06 24 4
gpt4 key购买 nike

我有一个 Java HashMap ,我需要限制其大小(50000 的数量级)。但我应该只删除最旧的项目。项目的时间戳存储在条目对象的字段中:

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

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

我还按时间戳的顺序将它们插入到 map 中。

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

最佳答案

HashMap 没有“oldest”,没有“first”,也没有order

另一方面,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, B=A, C=A, D=A}
{B=A, C=A, D=A, E=A}
{C=A, D=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

关于java - 从 HashMap 中删除最旧的对象以达到特定大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41184893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com