Use entrySet instead of keySet here.
52 System.out.println(" Starting with Game Start Tests ...");
53 game.start();
54 System.out.print(" Checking if every Player has got his Deck.");
55 for (Player player : game.getPlayerCardHashMap().keySet()) { 56 assertEquals(game.getPlayerCardHashMap().get(player).size(),7,"Player has got more ore to few Cards.");
57 }
58 System.out.println(" ✅");
Description
This method accesses the value of a Map entry, using a key that was retrieved from a keySet
iterator.
It is more efficient to use an iterator on the entrySet
of the map, to avoid the Map.get(key)
lookup.
Bad Practice
for (String key: map.keySet()) {
...
if (satisfiesCriteria(key))
value = map.get(key); // Inefficient
...
}
Recommended
for (Map.Entry<String, Integer> entry : map.entrySet()) {
...
if (satisfiesCriteria(entry.getKey())
value = entry.getValue();
...
}
While the performance benefits of this change may not be very high for smaller maps, it is worth making this change if you will be handling maps with very large capacities (entry count in the millions for example), and/or slower or bad hashing implementations.
References
- SpotBugs - WMI_WRONG_MAP_ITERATOR