JavaHashMap
Java HashMap
AHashMap stores items inkey/value pairs, where each key maps to a specific value.
It is part of thejava.util package and implements theMap interface.
Instead of accessing elements by an index (like withArrayList), you use akey to retrieve its associatedvalue.
AHashMap can store many different combinations, such as:
Stringkeys andIntegervaluesStringkeys andStringvalues
Create a HashMap
Create aHashMap object calledcapitalCities that will storeString keys andString values:
Example
import java.util.HashMap; // Import the HashMap classHashMap<String, String> capitalCities = new HashMap<>(); Now you can use methods likeput() to add key/value pairs,get() to retrieve a value by key, andremove() to delete an entry - all by using keys instead of index numbers.
Add Items
To add items to aHashMap, use theput() method:
Example
// Import the HashMap classimport java.util.HashMap;public class Main { public static void main(String[] args) { // Create a HashMap object called capitalCities HashMap<String, String> capitalCities = new HashMap<String, String>(); // Add keys and values (Country, City) capitalCities.put("England", "London"); capitalCities.put("India", "New Dehli"); capitalCities.put("Austria", "Wien"); capitalCities.put("Norway", "Oslo"); capitalCities.put("Norway", "Oslo"); // Duplicate capitalCities.put("USA", "Washington DC"); System.out.println(capitalCities); }}Note: In the example above, if the same key (like "Norway") is added more than once, thelatest value will overwrite the previous one, because keys in aHashMap must be unique.
Access an Item
To access a value in theHashMap, use theget() method and refer to its key:
Remove an Item
To remove an item, use theremove() method and refer to the key:
To remove all items, use theclear() method:
HashMap Size
To find out how many items there are, use thesize() method:
Note: The size only counts unique keys. If a key is added more than once, only the latest value is kept.
Loop Through a HashMap
Loop through the items of aHashMap with afor-each loop.
Note: Use thekeySet() method if you only want the keys, and use thevalues() method if you only want the values:
Example
// Print keysfor (String i : capitalCities.keySet()) { System.out.println(i);}Example
// Print valuesfor (String i : capitalCities.values()) { System.out.println(i);}Example
// Print keys and valuesfor (String i : capitalCities.keySet()) { System.out.println("key: " + i + " value: " + capitalCities.get(i));}Other Types
Keys and values in aHashMap are actually objects. In the examples above, we used objects of type "String". Remember that aString in Java is an object (not a primitive type). To use other types, such asint, you must specify an equivalentwrapper class:Integer. For other primitive types, use:Boolean for boolean,Character for char,Double for double, etc:
Example
Create aHashMap object calledpeople that will storeStringkeys andIntegervalues:
// Import the HashMap classimport java.util.HashMap;public class Main { public static void main(String[] args) { // Create a HashMap object called people HashMap<String, Integer> people = new HashMap<String, Integer>(); // Add keys and values (Name, Age) people.put("John", 32); people.put("Steve", 30); people.put("Angie", 33); for (String i : people.keySet()) { System.out.println("key: " + i + " value: " + people.get(i)); } }}When Order Matters
In the next chapter, you will learn aboutTreeMap, which stores key/value pairsin sorted order by key.
The var Keyword
From Java 10, you can use thevar keyword to declare aHashMap variable without writing the type twice. The compiler figures out the type from the value you assign.
This makes code shorter,but many developers still use the full type for clarity. Sincevar is valid Java, you may see it in other code, so it's good to know that it exists:
Example
// Without varHashMap<String, String> capitalCities = new HashMap<String, String>();// With varvar capitalCities = new HashMap<String, String>();The Map Interface
Note: Sometimes you will see bothMap andHashMap in Java code, like this:
import java.util.Map;import java.util.HashMap;Map<String, String> capitalCities = new HashMap<>();This means the variable (capitalCities) is declared as aMap (the interface), but it stores aHashMap object (the actual map). SinceHashMap implements theMap interface, this is possible.
It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later.
Complete HashMap Reference
For a complete reference of HashMap methods, go to ourJava HashMap Reference.

