Iterating through a HashMap in a For Each style

hashmap, java

Solution

Use the `values` collection

for(GameObject gameObject : character.values()) { 
    if(gameObject instanceof Stat) { }
}

Problem

I want to iterate through the 'character' HashMap and grab all of the'Stat' objects using something like a for each loop. For example I want to create a function called 'showStats'. To do this I want to be able to output all the 'stat' objects contained in the 'character' HashMap. Does anyone know how to do this? ``` HashMap<String, GameObject> character = new HashMap<String, GameObject>; character.put("Health", new Stat("Health",10)); character.put("Accuracy", new Stat("Accuracy",10)); character.put("Strength", new Stat("Strength",10)); character.put("Coins",new Item("Coins","Your Money")); character.put("Head",new BodyPart("Head")); ```

Original source