如何在 ArrayList 的到期时间使用 Guava Cache?

How to use Guava Cache with expiry time for an ArrayList?

我刚刚了解了 Guava 缓存,我看到的所有示例都使用了映射、键和值。

有什么方法可以将 guava 缓存用于 ArrayList 吗?

我有一个包含元素的 ArrayList,每个元素有 60 秒的生命周期,之后它应该被删除,我感谢任何建议。

是否可以在移除每个元素后触发一个方法?例如,如果从列表中删除了一个数字,我需要再次重新计算平均值。

Is there any way to use guava cache for an ArrayList?

Guava Cache 设计为按键查询。但是,您可以使用 ArrayList 的索引作为键或选择对象的一些唯一 属性 作为键(尽管据我了解,您需要按它们的顺序存储值已添加)。

And is it possible to trigger a method after removal of each element?

是的,在构建 Cache<K, V> 时,设置 RemovalListener<K,V>

例如:

Cache<String, String> cache = CacheBuilder.newBuilder()
    .expireAfterWrite(60, TimeUnit.SECONDS)
    .removalListener(new RemovalListener<String, String>() {
      public void onRemoval(RemovalNotification<String, String> removal) {
        // Compute the average here
      }          
    })
    .build();