Java HashMap Examples

Java HashMap

Java HashMap Implementation

Java HashMap Examples

Java HashMap vs HashTable

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


This will clear or empty the ageMap of all it's key/value pairs.

Add an entry


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


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()) {

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).

Your thoughts?