1. Introduction to Java HashMap
The Java HashMap is a special type of Collection. Unlike other collection classes, it represents Key-Value pairs. In this example, we will explore Map Interface and its functions. Then, we will move on to the implementing class HashMap. We will see how HashMap stores collection items using Key-Value pairs and how it offers different views on its internal data store.
2. Map Interface
The Map Interface is a contract for representing the Key-Value pairs. Here, Key will refer to the Value. So, when we have Key in hand, we can get the Value. For example, we can use the Product Id as Key and store the entire Product object as a Value. Since key is the one which gets you to the Value, the Key must be unique, and value may not be. The put and get are the frequently used methods of the Map interface. We will learn about them when we use its implementing class HashMap in this example.
3. Java HashMap & Key-Value Pair
The HashMap class implements the Map Interface and hence it represents the data items as Key-Value pairs. Have a look at the picture below:

Here, we can see a HashMap is holding three Key-Value pairs. Each Key is pointing to a Value. A Key-Value pair is called as an Entry. So, the above HashMap is having three Entries. In some programming languages, this concept is called a dictionary. Recall, the Value can have duplicate. Say, for example, it is possible for the Key3 to point to a Value, value 1, which is a duplicate. But HashMap does not allow the duplicates in Key.
4. Views of HashMap
We can extract three types of view from the Java HashMap. They are:
- Key View
- Value View
- Entry View
Key View contains only Keys and we can retrieve it using the method keyset
. The return value is a Set
as keys does not allow duplicates.
Value View contains only the Values and we can get it via the method call values
. Since HashMap allows duplicates for Values, the return value is a Collection
.
The Entry View is the collection of Entries which can be retrieved from the Java HashMap using the entrySet
method. As each entry is unique because of the Key, the return value is again a Set
.
The below picture shows the three views of the Java HashMap:

5. Using HashMap Methods
5.1 Adding Entries to HashMap Via put Method
While creating
HashMap, we can specify the Data Type of Key and Value. In the below code, at Line No 11, we specify the key as Integer and value as String. We store this Java
HashMap in a reference, ProductMap
. Next, we call
put method to add the entries to it. The first param is the Key and the second one is Value. At this stage, our HashMap is ready with six entries.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//Sample01: Required Packages import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Iterator; //Sample 02: Create HashMap Map<Integer, String> ProductMap = new HashMap<Integer,String>(); //Sample 03: Add Key, Value Pairs ProductMap.put(101, "Pen"); ProductMap.put(102, "Pencil"); ProductMap.put(103, "Rubber"); ProductMap.put(104, "Writing Pad"); ProductMap.put(105, "Clips"); ProductMap.put(106, "Sharpner"); |
5.2 Retrieving Entries From HashMap
We can retrieve a Value using the get method. The method takes a Key and returns the associated Value. Below is the code:
1 2 3 4 5 6 |
//Sample 04: Get Value for Known Keys System.out.println("Product 103 is: " + ProductMap.get(103)); System.out.println("Product 106 is: " + ProductMap.get(106)); System.out.println("========================================"); |
Output of the above code snippet:
1 2 3 4 |
Product 103 is: Rubber Product 106 is: Sharpner ======================================== |
5.3 Replace Value Through Key
The
replace method of the Java HashMap
takes two parameters. First one is the Key which exists in the HashMap and the second one is the new Value which needs to be mapped to the Key. When a Key is found, the method replaces the Value and returns the old mapped Value to the caller. Code snippet is below:
1 2 3 4 5 |
//Sample 05: Replace a Value for the Given Key String oldValue = ProductMap.replace(102, "Microtip Pencil" ); System.out.println("Product 102 is: " + ProductMap.get(102)); System.out.println("Product 102 previously was : " + oldValue); System.out.println("========================================"); |
Output:
1 2 3 |
Product 102 is: Microtip Pencil Product 102 previously was : Pencil |
5.4 The containsKey and containsValue Methods
The
containsKey method walks through the Keys present in the HashMap
and returns true when the Key presents. The
containsValue also works the same way. Below code uses both the methods:
1 2 3 4 5 6 7 |
//Sample 06: Test existence of Key and/or Value System.out.println("Is key 103 Present?: " + ProductMap.containsKey(103)); System.out.println("Is key 103 Present?: " + ProductMap.containsKey(108)); System.out.println("Is Pen Available?: " + ProductMap.containsValue("Pen")); |
5.5 Printing All Keys of Java HashMap
The
keySet method of the Java HashMap
returns all the keys stored in it. Since the return value is a set, the printKeys
custom function takes a Set
as an argument. The function then iterates through this Key Set to print it in the console output window. We can see the
keySet function is giving us the Key View of the HashMap
.
1 2 3 4 5 6 7 8 9 10 |
//Sample 07: Key View Set<Integer> Keys = ProductMap.keySet(); printKeys(Keys); //Sample 07a: Key Iterator private static void printKeys(Set<Integer> Keys) { Iterator<Integer> KeyItr = Keys.iterator(); while(KeyItr.hasNext()) System.out.println(KeyItr.next()); } |
5.6 Printing All Values of Java HashMap
We can get the Value View of the Java HashMap via the
values method. Since values in the HashMap
are unique it returns a Collection
not the Set
. The printValue
custom function grabs iterator from this Collection
and print all the values present in the HashMap
. Below is the code:
1 2 3 4 5 6 7 8 9 10 |
//Sample 08: Value View Collection<String> Values = ProductMap.values(); printValue(Values); //Sample 08a: Value Iterator private static void printValue(Collection<String> Values) { Iterator<String> ValueItr = Values.iterator(); while(ValueItr.hasNext()) System.out.println(ValueItr.next()); } |
5.7 Printing Key-Value Pairs of Java HashMap
In the below code, at line 2-3, we get the Key-Value pair by calling the
entrySet function on Java HashMap. The entries (Key-Value pair) are unique, as Keys are unique. So, the Entries returned is a Set. Note how we declared the Set reference at line 2. An Entry is a Key and Value combination. The data type of Key is Integer and data type of Value is String. So, we declare Entry as Entry<Integer, String>
. The Set is the collection of these Entries and hence the type goes as Set< Entry<Integer, String>>
.
In the printEntrySet
function, we get iterator and it over the Entry<Integer, String>
. The next
method of the iterator returns an Entry object, which is a Key-Value pair. We can use
getKey method to get the Key and
getValue method to get the Value. Our custom method iterates over all the Key-Value pairs in the Java HashMap
and prints that in the console output window.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//Sample 09: Entry View Set<Entry<Integer,String>> KeyValuePairs= ProductMap.entrySet(); printEntrySet(KeyValuePairs); //Sample 09a: Iterate EntrySet private static void printEntrySet( Set<Entry<Integer, String>> KeyValuePairs) { Iterator<Entry<Integer, String>> MapItr = KeyValuePairs.iterator(); System.out.println("KEY VALUE"); System.out.println("=== ====="); while(MapItr.hasNext()) { Entry<Integer,String> thePair = MapItr.next(); System.out.print(thePair.getKey()); System.out.print(" "); System.out.println(thePair.getValue()); } } |
Output:
1 2 3 4 5 6 7 8 |
KEY VALUE === ===== 101 Pen 102 Microtip Pencil 103 Rubber 104 Writing Pad 105 Clips 106 Sharpner |
6. Complete Code Example – Java HashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
//Sample01: Required Packages import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Iterator; public class HashSetTest { public static void main(String[] args) { //Sample 02: Create HashMap Map<Integer, String> ProductMap = new HashMap<Integer,String>(); //Sample 03: Add Key, Value Pairs ProductMap.put(101, "Pen"); ProductMap.put(102, "Pencil"); ProductMap.put(103, "Rubber"); ProductMap.put(104, "Writing Pad"); ProductMap.put(105, "Clips"); ProductMap.put(106, "Sharpner"); //Sample 04: Get Value for Known Keys System.out.println("Product 103 is: " + ProductMap.get(103)); System.out.println("Product 106 is: " + ProductMap.get(106)); System.out.println("========================="); //Sample 05: Replace a Value for the Given Key String oldValue = ProductMap.replace(102, "Microtip Pencil" ); System.out.println("Product 102 is: " + ProductMap.get(102)); System.out.println("Product 102 previously was : " + oldValue); System.out.println("======================="); //Sample 06: Test existence of Key and/or Value System.out.println("Is key 103 Present?: " + ProductMap.containsKey(103)); System.out.println("Is key 108 Present?: " + ProductMap.containsKey(108)); System.out.println("Is Pen Available?: " + ProductMap.containsValue("Pen")); //Sample 07: Key View Set<Integer> Keys = ProductMap.keySet(); printKeys(Keys); //Sample 08: Value View Collection<String> Values = ProductMap.values(); printValue(Values); //Sample 09: Entry View Set<Entry<Integer,String>> KeyValuePairs= ProductMap.entrySet(); printEntrySet(KeyValuePairs); } //Sample 07a: Key Iterator private static void printValue(Collection<String> Values) { Iterator<String> ValueItr = Values.iterator(); while(ValueItr.hasNext()) System.out.println(ValueItr.next()); } //Sample 08a: Value Iterator private static void printKeys(Set<Integer> Keys) { Iterator<Integer> KeyItr = Keys.iterator(); while(KeyItr.hasNext()) System.out.println(KeyItr.next()); } //Sample 09a: Iterate EntrySet private static void printEntrySet( Set<Entry<Integer, String>> KeyValuePairs) { Iterator<Entry<Integer, String>> MapItr = KeyValuePairs.iterator(); System.out.println("KEY VALUE"); System.out.println("=== ====="); while(MapItr.hasNext()) { Entry<Integer,String> thePair = MapItr.next(); System.out.print(thePair.getKey()); System.out.print(" "); System.out.println(thePair.getValue()); } } } |
7. Watch Java HashMap as YouTube Video
- Performance Study – ArrayList vs TreeSet
- AWT GridBagLayout GridBagConstraints Weightx, WeightY & Fill
Categories: Java
Tags: entrySet, HashMap.contains, HashMap.get, HashMap.put, HashMap.values, keySet