Consider user Map.Entry for whole map iteration instead of
getKeys() and then get value by key.
check could simply check while/for for such case. This check will not find all
weird cases but will help significantly with major cases, that are done as C++ habit, refactoring, .....
http://sourceforge.net/p/checkstyle/feature-requests/586/
from Check JavaDoc:
This check can help you to write the whole for-each map iteration more correctly:
If you iterate over a map using map.keySet() or map.entrySet(), but your code uses only map values, Check will propose you to use map.values() instead of map.keySet() or map.entrySet(). Replacing map.keySet() or map.entrySet() with map.values() for such cases can a bit improve an iteration performance.
Bad:
for (Map.Entry; entry : map.entrySet()){
System.out.println(entry.getValue());
}
for (String key : map.keySet(){
System.out.println(map.get(key));
}
Good:
for (String value : map.values()){
System.out.println(value);
}
If you iterate over a map using map.entrySet(), but never call entry.getValue(), Check will propose you to use map.keySet() instead of map.entrySet(). to iterate over map keys only.
Bad:
for (Map.Entry entry : map.entrySet()){
System.out.println(entry.getKey());
}
Good:
for (String key : map.keySet()){
System.out.println(key);
}
If you iterate over a map with map.keySet() and use both keys and values, check will propose you to use map.entrySet() to improve an iteration performance by avoiding search operations inside a map. For this case, iteration can significantly grow up a performance.
Bad:
for (String key : map.keySet()){
System.out.println(key + " " + map.get(key));
}
Good:
for (Map.Entry entry : map.entrySet()){
System.out.println(entry.getValue() + " " + entry.getKey());
}