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 tmpList
assignment.
I do not understand why this is inefficient. In fact the keys
list is computed only once.
Any comment? Thanks.
In Java HashMap, we can iterate through its keys, values, and key/value mappings.
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.
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.
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) {
// ...
}
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 + ")" );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With