I have a HashMap:
private HashMap<TypeKey, TypeValue> example = new HashMap<TypeKey, TypeValue>();
Now I would like to run through all the values and print them.
I wrote this:
for (TypeValue name : this.example.keySet()) {
System.out.println(name);
}
It doesn’t seem to work.
What is the problem?
EDIT:
Another question: Is this collection zero based? I mean if it has 1 key and value will the size be 0 or 1?
keySet()only returns a set of keys from your hash map, you should iterate this key set and the get the value from the hash map using these keys.In your example, the type of the hash map’s key is
TypeKey, but you specifiedTypeValuein your genericfor-loop, so it cannot be compiled. You should change it to:Update for Java8:
If you don’t require to print key value and just need the hash map value, you can use others’ suggestions.
The collection returned from
keySet()is aSet. You cannot get the value from a set using an index, so it is not a question of whether it is zero-based or one-based. If your hash map has one key, thekeySet()returned will have one entry inside, and its size will be 1.