Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding map.get(key) method

Tags:

java

keyset

I have the following code but i saw that retrieving values from a Map while iterating over the Map keys with keySet() is a mistake even with findBugs i get the warning WMI_WRONG_MAP_ITERATOR

for(String elementId : mapElements.keySet()){

     element = mapElements.get(elementId); 

     doSomething(element);
}

so why exactly is this not good and how can i fix it ?

Thanks.

like image 207
Mouna Cheikhna Avatar asked Sep 27 '11 13:09

Mouna Cheikhna


1 Answers

If you're iterating over everything in a map, you might as well do:

for (Map.Entry<String, String> entry : mapElements.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    // Use the key and the value
}

Or if you don't really need the key, just iterate over the values:

for (String value : mapElements.values()) {
    doSomething(value);
}

EDIT: syntax

like image 99
Jon Skeet Avatar answered Nov 20 '22 10:11

Jon Skeet