Blog
Comment
Java HashMap Examples
Java HashMap Interview Questions
Create a HashMap
HashMap<String, Integer> ageMap = new HashMap();
This creates an empty HashMap ageMap. Notice how the key/value types are specified via <String, Integer>.
Clear a HashMap
ageMap.clear();
This will clear or empty the ageMap of all it's key/value pairs.
Add an entry
ageMap.put("Sam",40);
In this example, we add a key/value pair to the ageMap
. Notice how we specify both the key and value in their respective types put("Sam", 40).
For more on how this is working under the hood, be sure to check out Java HashMap implementation.
Remove an entry
ageMap.remove("Sam")
This removes the entry with the specified key. Notice how we provide the key "Sam" we wan't to remove.
Loop through a HashMap
for(String i : ageMap.keySet()) {
System.out.println(ageMap.get(i));
}
We can loop through a HashMap similar to other collections by taking a list of keys ageMap.keySet(). We iterate through the keys and can print the value for each entry via ageMap.get(i).