Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 901
Luixv Avatar asked Mar 25 '11 09:03

Luixv


People also ask

Can you iterate over a HashMap Java?

In Java HashMap, we can iterate through its keys, values, and key/value mappings.

Can you iterate through a hash set?

There are three simple ways to iterate over a HashSet, which is the following : Using Iterator. Without using Iterator (using for loop) Using for-each loop.

How do I efficiently iterate over each entry in a Java list?

forEach() Since Java 8, we can use the forEach() method to iterate over the elements of a list. This method is defined in the Iterable interface, and can accept Lambda expressions as a parameter.


2 Answers

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) {
    // ...
}
like image 130
Jesper Avatar answered Oct 05 '22 23:10

Jesper


you're getting all the keys and then you search for every key in the collection

a Map.EntrySet iteration would be much faster, a small example:

But you also should use generics...

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 + ")" );
      }
like image 34
sharpner Avatar answered Oct 06 '22 00:10

sharpner