Printing HashMap In Java
To print both key and value, use the following:
for (Object objectName : example.keySet()) {
System.out.println(objectName);
System.out.println(example.get(objectName));
}
Assuming you have a Map<KeyType, ValueType>
, you can print it like this:
for (Map.Entry<KeyType, ValueType> entry : map.entrySet()) {
System.out.println(entry.getKey()+" : "+entry.getValue());
}
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 specified TypeValue
in your generic for-loop
, so it cannot be compiled. You should change it to:
for (TypeKey name: example.keySet()) {
String key = name.toString();
String value = example.get(name).toString();
System.out.println(key + " " + value);
}
Update for Java8:
example.entrySet().forEach(entry -> {
System.out.println(entry.getKey() + " " + entry.getValue());
});
If you don't require to print key value and just need the hash map value, you can use others' suggestions.
Another question: Is this collection is zero base? I mean if it has 1 key and value will it size be 0 or 1?
The collection returned from keySet()
is a Set
. 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, the keySet()
returned will have one entry inside, and its size will be 1.
A simple way to see the key value pairs:
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
System.out.println(Arrays.asList(map)); // method 1
System.out.println(Collections.singletonList(map)); // method 2
Both method 1 and method 2 output this:
[{b=2, a=1}]