Search code examples
javaoptimizationiterationkeyset

Java Iteration over 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 am getting a warning from "findBugs" telling the following:

Method myMethod makes inefficient use of keySet iterator instead of entrySet iterator. The warning is done at the tmpListassignment.

I do not understand why this is inefficient. In fact the keyslist is computed only once. Any comment? Thanks.


Solution

  • Instead of iterating over the keySet and calling get to get the corresponding value for 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
    }
    

    That way you don't have to do a lookup in the map for every key; you directly get the key and value in one go.

    Also, declare your Map with type parameters:

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