java - 如何使用带有过期时间的 Guava Cache 的 ArrayList?

标签 java arraylist google-guava-cache

我刚刚发现 Guava Caching,我看到的所有示例都使用映射、键和值。

有没有办法将 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();

关于java - 如何使用带有过期时间的 Guava Cache 的 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45898103/

相关文章:

java - 按日期和 ID 对 ArrayList<Usable> 进行排序

java - 由于类型不兼容,接收不同通用列表的方法不起作用

java - mongodb sql in 语句等效

java - org.postgresql.util.PSQLException : The column index is out of range: 2, 列数:1

java - 简单 Java 数学问题生成器运行和终止

java - 如何将 arrayList 元素转换为二维数组?

java - 如何使用 Guava 的 CacheBuiler 作为 ConcurrentLRUCache

java - 对调用静态方法的类进行单元测试

java - 将第二个参数传递给 Guava Cache load() 方法

java - 使用 DrawerLayout 检查当前打开的 fragment 位置