Java iteration on a keyset

I have the following java code:

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
   }
}

I get a warning from "findbugs" telling me the following:

Invalid method mymethod. Use keyset iterator instead of entryset iterator This warning is completed at the tmplist alignment

I don't understand why this is inefficient In fact, keylist is calculated only once Any comments? thank you.

Solution

Instead of iterating over the keyset and calling get to get the corresponding value of each key, iterate over the entryset:

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
}

So you don't have to look up every key on the map; You get the key and value directly once

In addition, declare your map with type parameters:

public void myMethod (final Map<String,List<FeatureKey>> pFeatureGroupsFromPackage) {
    // ...
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>