Java Iteration over a keySet

2022-09-02 23:38:42

我有以下Java代码:

public void myMethod (final Map pFeatureGroupsFromPackage) {

   final Set<String> keys = pFeatureGroupsFromPackage.keySet();

   for (final String key : keys) {
           tmpList = (List<FeatureKey>) pFeatureGroupsFromPackage.get(key);
    // do whatever
   }
}

我从“findBugs”那里得到了一个警告,上面写着:

方法使 keySet 迭代器而不是 entrySet 迭代器的使用效率低下。警告在分配时完成。myMethodtmpList

我不明白为什么这是低效的。实际上,该列表仅计算一次。任何意见?谢谢。keys


答案 1

不是迭代 和 调用以获取每个键的相应值,而是循环访问 :keySetgetentrySet

final Set<Map.Entry<String, List<FeatureKey>>> entries = pFeatureGroupsFromPackage.entrySet();

for (Map.Entry<String, List<FeatureKey>> entry : entries) {
    String key = entry.getKey();
    List<FeatureKey> tmpList = entry.getValue();

    // do whatever
}

这样,您就不必在地图上查找每个键。您可以一次性直接获得密钥和值。

此外,声明您的 with 类型参数:Map

public void myMethod (final Map<String, List<FeatureKey>> pFeatureGroupsFromPackage) {
    // ...
}

答案 2

你得到了所有的钥匙,然后你搜索集合中的每个钥匙

Map.EntrySet迭代会快得多,举个小例子:

但是您还应该使用泛型...

Set entries = map.entrySet();
      Iterator entryIter = entries.iterator();
      System.out.println("The map contains the following associations:");
      while (entryIter.hasNext()) {
         Map.Entry entry = (Map.Entry)entryIter.next();
         Object key = entry.getKey();  // Get the key from the entry.
         Object value = entry.getValue();  // Get the value.
         System.out.println( "   (" + key + "," + value + ")" );
      }