I have a HashMap
:
private HashMap example = new HashMap();
Now I would lik
keySet() only returns a set of keys from your hashmap, you should iterate this key set and the get the value from the hashmap using these keys.
In your example, the type of the hashmap'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 hashmap 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 hashmap has one key, the keySet() returned will have one entry inside, and its size will be 1.
map.forEach((key, value) -> System.out.println(key + " " + value));
Using java 8 features
Java 8 new feature forEach
style
import java.util.HashMap;
public class PrintMap {
public static void main(String[] args) {
HashMap<String, Integer> example = new HashMap<>();
example.put("a", 1);
example.put("b", 2);
example.put("c", 3);
example.put("d", 5);
example.forEach((key, value) -> System.out.println(key + " : " + value));
// Output:
// a : 1
// b : 2
// c : 3
// d : 5
}
}
A simple print statement with the variable name which contains the reference of the Hash Map would do :
HashMap<K,V> HM = new HashMap<>(); //empty
System.out.println(HM); //prints key value pairs enclosed in {}
This works because the toString()
method is already over-ridden in the AbstractMap class
which is extended by the HashMap Class
More information from the documentation
Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).
Useful to quickly print entries in a HashMap
System.out.println(Arrays.toString(map.entrySet().toArray()));
You have several options