【问题标题】:How to iterate over LoadingCache google class如何迭代 LoadingCache 谷歌类
【发布时间】:2023-04-03 23:29:01
【问题描述】:

我有一个像这样的加载缓存类:

LoadingCache<Integer, List<Parent>> parents

其中Parent 是具有iddescriptionhomenickname 的类

我想打印 parents 对象内的所有值

我试图做类似的事情:

parents.keys()

但我找不到 LoodingCache 对象的那个方法

【问题讨论】:

    标签: java list generics iterator


    【解决方案1】:

    您可以改用asMap() 方法:

      /**
       * Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to
       * the map directly affect the cache.
       */
      ConcurrentMap<K, V> asMap();
    

    【讨论】:

      【解决方案2】:

      这个呢?:

      Set<Integer> s = parents.asMap().keySet();
              Iterator<Integer> it = s.iterator();
              while (it.hasNext()) {
                  int n = it.next();
                  try {
                      List<Parent> list = parents.get(n);
                      for (Parent l : list) {
                          System.out.println(String.format(
                                  "id = %s, description = %s, home = %s",
                                  l.getId(), l.getDescription(), l.getHome())); // you can do more than printing to standard output 
                      }
                  } catch (ExecutionException e) {
                      LOG.error(e.getMessage(), e); // you can do whatever you want
                  }
              }
      

      LoadingCache 有一个名为asMap的方法

      get 方法抛出三个异常,分别是: ExecutionException UncheckedExecutionExceptionExecutionError

      【讨论】:

        【解决方案3】:

        如果你只想打印所有Parent 对象,这真的很简单。

        for (List<Parent> parentsGroup : parents.asMap().values()) {
          for (Parent parent : parentsGroup) {
            System.out.println(parent); // or whatever
          }
        }    
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-15
          • 2011-08-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多