gpt4 book ai didi

java - 是否有任何数据结构可以保留迭代顺序并删除旧记录?

转载 作者:搜寻专家 更新时间:2023-11-01 03:33:12 24 4
gpt4 key购买 nike

我有一个用例,我想从多个线程将条目填充到数据结构中,因此它必须是线程安全的,并且在达到特定大小后开始删除旧记录。而且我还想以相同的插入顺序迭代数据结构。

所以我决定在这里使用 Guava Cache 但令我惊讶的是 Guava asMap() 方法不会以任何特定顺序返回元素。

private final Cache<Integer, Integer> cache =
CacheBuilder.newBuilder().maximumSize(10)
.removalListener(
RemovalListeners.asynchronous(new CustomListener(), executorService)
).build();

cache.put(1, 1);
cache.put(2, 2);
cache.put(3, 3);
cache.put(4, 4);
cache.put(5, 5);
cache.put(6, 6);

for (Entry<Integer, Integer> entry : cache.asMap().entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}

输出:

2=2
6=6
1=1
4=4
3=3
5=5

我可以在这里使用什么其他有效的数据结构,它可以为我保留迭代顺序,还可以可靠地一旦达到大小就删除旧记录,并为我所在的删除监听器提供一些回调可以找出哪些记录被丢弃了?

任何例子都会有很大的帮助。我正在使用 Java 7,还不能切换到 Java 8。

所以我应该能够在迭代时得到这样的东西,而且它应该自动删除旧记录:

1=1
2=2
3=3
4=4
5=5
6=6

最佳答案

对于 Java 7,您可以使用 Caffeine的前身,ConcurrentLinkedHashMap :

ConcurrentMap<Integer, Integer> cache =
new ConcurrentLinkedHashMap.Builder<Integer, Integer>()
.maximumWeightedCapacity(10)
.build();

cache.put(1, 1);
cache.put(2, 2);
cache.put(3, 3);
cache.put(4, 4);
cache.put(5, 5);
cache.put(6, 6);

for (Entry<Integer, Integer> entry : cache.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}

输出

1=1
2=2
3=3
4=4
5=5
6=6

参见 ExampleUsage · ben-manes/concurrentlinkedhashmap Wiki了解更多详情。

关于java - 是否有任何数据结构可以保留迭代顺序并删除旧记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41753999/

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