HashMap

Hashmap Java Example (with video)

Java HashMap is a member of the Java Collection Framework and is a very common way to collect and retrieve data. HashMap represents a data structure that offers key-value pairs storing, based on hashing. HashMap Methods provided, allow you to add, modify and remove elements when needed.

In this example, we are going to show how we can create a simple HashMap and a HashMap where multiple values correspond to a key, as well as some basic functions to add and retrieve HashMap's objects.

HashMap is a member of the Java Collection Framework and is a very common way to collect and retrieve data. HashMap represents a data structure that offers key-value pairs storing, based on hashing.

You can also check this tutorial in the following video:

HashMap Java Example – Video

1. Syntax of the HashMap Java class

The general expression of HashMap Class is Class HashMap<K,V>, where:

  • K: specifies the type of keys maintained by this map
  • V: defines the type of mapped values

HashMap includes some different expressions for its constructor:

The arguments are:

  • initialCapacity: is the initial number of buckets of the hash table, where its default value is 16.
  • loadFactor: represents the percentage of how full the hash table can be, before increasing its capacity. Its default value is 0.75

2. Properties of HashMap

  • Java HashMap class contains values based on the key.
  • Java HashMap class contains only unique keys.
  • Java HashMap class may have one null key and multiple null values.
  • Java HashMap class is non-synchronized.
  • Java HashMap class maintains no order.
  • The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

3. Hashmap in Collection hierarchy

HashMap class extends AbstractMap class and implements Map interface. As shown in the following figure-

Hashmap Java - Hashmap in Collection hierarchy
Hashmap in Collection hierarchy

4. Important methods in Java HashMap

Following are the method present in java.util.HashMap class-

  1. clear(): Removes all of the mappings from this map.
  2. clone(): Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
  3. compute(K key, BiFunction remappingFunction): Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
  4. computeIfAbsent(K key, Function mappingfunction): If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
  5. computeIfPresent(K key, BiFunction remappingfunction): If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
  6. containsKey(Object key): Returns true if this map contains a mapping for the specified key.
  7. containsValue(Object value): Returns true if this map maps one or more keys to the specified value.
  8. entrySet(): Returns a Set view of the mappings contained in this map.
  9. forEach(): Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
  10. get(Object key): Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  11. getOrDefault(Object key, V defaultValue): Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
  12. isEmpty(): Returns true if this map contains no key-value mappings.
  13. keySet(): Returns a Set view of the keys contained in this map.
  14. merge(K key, V value, BiFunction remapping Function): If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
  15. put(K key, V value): Associates the specified value with the specified key in this map.
  16. putAll(Map m): Copies all of the mappings from the specified map to this map.
  17. putIfAbsent(K key, V value): If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
  18. remove(Object key): Removes the mapping for the specified key from this map if present.
  19. remove(Object key, Object value): Removes the entry for the specified key only if it is currently mapped to the specified value.
  20. replace(K key, V value): Replaces the entry for the specified key only if it is currently mapped to some value.
  21. replace(K key, V oldValue, V newValue): Replaces the entry for the specified key only if currently mapped to the specified value.
  22. replaceAll(BiFunction function): Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
  23. size(): Returns the number of key-value mappings in this map.
  24. values(): Returns a Collection view of the values contained in this map.

4.1 compute(), computeIfAbsent() and computeIfPresent() methods in Java HashMap

Compute Method Demo

HashMap<Integer, String> nameMap = new HashMap();
nameMap.put(1, "John");
nameMap.put(2, "Jack");

System.out.println("Initial map: " + nameMap);

nameMap.compute(1, (key, val) -> val.concat(" Smith"));
System.out.println("Map after re evaluating the value for key 1: " + nameMap);
// will throw NullPointerException because key is not present
//nameMap.compute(3, (key, val) -> val.concat(" Smith"));

//Since key 4 is not present it will get inserted with key 4 and value Steve
nameMap.computeIfAbsent(4, key -> "Steve");
System.out.println("Map after re evaluating the value for key 4 if it is absent: " + nameMap);
//Since key 1 is present it will not get inserted
nameMap.computeIfAbsent(1, key -> "Steve");
System.out.println("Map after re evaluating the value for key 1 if it is absent: " + nameMap);

//Since key 4 is present its value will get calculated as per mapping function
nameMap.computeIfPresent(4, (key, val) -> val.concat(" Smith"));
System.out.println("Map after re evaluating the value for key 1 if it is Present: " + nameMap);
//Since key 5 is not present so its value will not get calculated
nameMap.computeIfPresent(5, (key, val) -> val.concat(" Smith"));
System.out.println("Map after re evaluating the value for key 1 if it is Present: " + nameMap);

Explanation:

  • In the above code first, we are creating a map object with initial value as {1=John, 2=Jack}.
  • At line 7 we are recomputing the value for the key 1 and appending “Smith” to its original value.
  • At line 13 we are computing the value for the key 4 if the key does not already exist and storing “Smith” at key 4.
  • Again at line 16, we are computing the value for the key 1 if the key does not already exist and storing “Steve” at key 1. Since the key already present so it will not affect the map object.
  • At line 20 since key 4 already its value will get calculated as per mapping function.
  • At line 23 Since key 5 is not present so its value will not get calculated.

Now let’s see the output:

Result

Initial map: {1=John, 2=Jack}
Map after re evaluating the value for key 1: {1=John Smith, 2=Jack}
Map after re evaluating the value for key 4 if it is absent: {1=John Smith, 2=Jack, 4=Steve}
Map after re evaluating the value for key 1 if it is absent: {1=John Smith, 2=Jack, 4=Steve}
Map after re evaluating the value for key 1 if it is Present: {1=John Smith, 2=Jack, 4=Steve Smith}
Map after re evaluating the value for key 1 if it is Present: {1=John Smith, 2=Jack, 4=Steve Smith}

4.2 containsKey() and containsValue() method in Java HashMap

Contains Method Demo

HashMap<Integer, String> nameMap = new HashMap();
nameMap.put(1, "John");
nameMap.put(2, "Jack");
//returns true because key 1 is present in map
System.out.println("Is key 1 present in map(" + nameMap + "? : " + nameMap.containsKey(1));
//returns false because key 3 is not present in map
System.out.println("Is key 3 present in map(" + nameMap + "? : " + nameMap.containsKey(3));

//returns true because value John is present in map
System.out.println("Is value John present in map(" + nameMap + "? : " + nameMap.containsValue("John"));
//returns false because value Steve is not present in map
System.out.println("Is value Steve present in map(" + nameMap + "? : " + nameMap.containsValue("Steve"));

Explanation:

  • In the above code first, we are creating a map object with initial value as {1=John, 2=Jack}.
  • At line 5 and 7 we are calling containsKey() method for the existence of key 1 and 3 respectively. Since the key 1 is already present in the map it returns true but for key 3 because it’s not there on the map so it returns false.
  • At line 10 and 12, we are calling containsValue() method for the existence of values “John” and “Steve” respectively. Since the value “John” is already present in the map it returns true but for value “Steve” because it’s not there on the map so it returns false.

Result

Is key 1 present in map({1=John, 2=Jack}? : true
Is key 3 present in map({1=John, 2=Jack}? : false
Is value John present in map({1=John, 2=Jack}? : true
Is value Steve present in map({1=John, 2=Jack}? : false

4.3 get() and getOrDefault() method in Java HashMap

Get Method Demo

HashMap<Integer, String> nameMap = new HashMap();
nameMap.put(1, "John");
nameMap.put(2, "Jack");

//Since value for key 1 is present in map so get() returns its value
System.out.println("value for key 1 in map(" + nameMap + " is : " + nameMap.get(1));
//Since value for key 3 is not present in map so get() returns null
System.out.println("value for key 3 in map(" + nameMap + " is : " + nameMap.get(3));

//Since value for key 1 is present in map so getOrDefault() returns its value
System.out.println("value for key 1 in map(" + nameMap + " is present in map and value is: " + nameMap.getOrDefault(1, "Steve"));
//Since value for key 1 is present in map so getOrDefault() returns default value
System.out.println("value for key 3 in map(" + nameMap + " is not present so default value is: " + nameMap.getOrDefault(3, "Steve"));

Explanation:

  • In the above code first, we are creating a map object with initial value as {1=John, 2=Jack}.
  • At line 5 and 7, we are calling get() method for key 1 and 3. Since Key 1 is present in the map so its value gets returned but for key 3 is not present in the map so null value gets returned back.
  • At line 11 and 13, we are calling getOrDefault() method for key 1 and 3. Since Key 1 is present in the map so its value gets returned but for key 3 is not present in the map so default value “Steve” gets returned back.

Result

value for key 1 in map({1=John, 2=Jack} is : John
value for key 3 in map({1=John, 2=Jack} is : null
value for key 1 in map({1=John, 2=Jack} is present in map and value is: John
value for key 3 in map({1=John, 2=Jack} is not present so default value is: Steve

4.4 put(), putIfAbsent() and putAll() method in Java HashMap

Put Method Demo

HashMap<Integer, String> nameMap = new HashMap();
nameMap.put(1, "John");

System.out.println("Initial map: " + nameMap);

System.out.println("Adding element key 2 and value Jack");
nameMap.put(2, "Jack");
System.out.println("Updated map: " + nameMap);

System.out.println("Adding element key 2 and value Jack1 if key 2 is absent");
nameMap.putIfAbsent(2, "Jack");
System.out.println("Updated map: " + nameMap);

System.out.println("Adding element key 3 and value Steve if key 2 is absent");
nameMap.putIfAbsent(3, "Steve");
System.out.println("Updated map: " + nameMap);

HashMap anotherNameMap = new HashMap();
anotherNameMap.put(4, "Alex");

System.out.println("Adding map "+ anotherNameMap+" to map "+nameMap);
nameMap.putAll(anotherNameMap);

System.out.println("Updated map: " + nameMap);

Explanation:

  • In the above code first, we are creating a map object with initial value as {1=John}.
  • At line 7 we are using put() to simply inserting an entry as key 2 and value Jack”.
  • At line 11 we are using putIfAbsent() to inserting an entry as key 2 and value Jack1. Since key 2 is already present it will not do anything.
  • At line 15 we are using putIfAbsent() to inserting an entry as key 3 and value Steve. Since the key 3 is not present so it gets inserted into the map.
  • At line 18 and 19, we are creating another map having Key = 4 and value Alex and at line, we are using putAll() method to insert elements of this map to the original map.

Now let’s have a look over the output of the above code-

Result

Initial map: {1=John}
Adding element key 2 and value Jack
Updated map: {1=John, 2=Jack}
Adding element key 2 and value Jack1 if key 2 is absent
Updated map: {1=John, 2=Jack}
Adding element key 3 and value Steve if key 2 is absent
Updated map: {1=John, 2=Jack, 3=Steve}
Adding map {4=Alex} to map {1=John, 2=Jack, 3=Steve}
Updated map: {1=John, 2=Jack, 3=Steve, 4=Alex}

4.5 remove() in Java HashMap

Remove Method Demo

HashMap<Integer, String> nameMap = new HashMap();
nameMap.put(1, "John");
nameMap.put(2, "Jack");
nameMap.put(3, "Steve");
nameMap.put(4, "Alex");
System.out.println("Initial map: " + nameMap);

System.out.println("Removing entry with key 1");
nameMap.remove(1);
System.out.println("Updated map: " + nameMap);

//Since no key value pair matches no action will be taken
System.out.println("Removing entry with key 3 and value Steve1");
nameMap.remove(3, "Steve1");
System.out.println("Updated map: " + nameMap);

//Since key value pair matches it will remove corresponding entry from map
System.out.println("Removing entry with key 3 and value Steve");
nameMap.remove(3, "Steve");
System.out.println("Updated map: " + nameMap);

Explanation:

  • In the above code first, we are creating a map object with initial value as {1=John, 2=Jack, 3=Steve, 4=Alex}.
  • At line 9 we are calling remove() method with one argument to remove the entry with key = 1. Since it is already there on the map so it will get removed.
  • At line 9 we are calling remove() method with two arguments to remove the entry with key = 3 and value = Steve1. Since no key-value pair matches, no action will be taken.
  • At line 9 we are calling remove() method with two arguments to remove the entry with key = 3 and value = Steve. Since key-value pair matches, it will remove the corresponding entry from map.

Result

Initial map: {1=John, 2=Jack, 3=Steve, 4=Alex}
Removing entry with key 1
Updated map: {2=Jack, 3=Steve, 4=Alex}
Removing entry with key 3 and value Steve1
Updated map: {2=Jack, 3=Steve, 4=Alex}
Removing entry with key 3 and value Steve
Updated map: {2=Jack, 4=Alex}

4.6 replace() and replaceAll() method in Java HashMap

Replace Method Demo

HashMap<Integer, String> nameMap = new HashMap();
nameMap.put(1, "John");
nameMap.put(2, "Jack");
System.out.println("Initial map: " + nameMap);

System.out.println("Replacing value of entry with key 1 with Steve in map: " + nameMap);
nameMap.replace(1, "Steve");
System.out.println("Updated map: " + nameMap);

System.out.println("Replacing value of entry with key 1 value Steve with John in map: " + nameMap);
nameMap.replace(1, "Steve", "John");
System.out.println("Updated map: " + nameMap);

System.out.println("Replacing value of entry with key 1 value John1 with John in map: " + nameMap);
nameMap.replace(1, "John1", "Steve");
System.out.println("Updated map: " + nameMap);

System.out.println("Replacing value of all entries original value plus \"Smith\": " + nameMap);
nameMap.replaceAll((key, val) -> val.concat(" Smith"));
System.out.println("Updated map: " + nameMap);

Explanation:

  • In the above code first, we are creating a map object with initial value as {1=John, 2=Jack}.
  • At line 7 we are calling replace() method with 2 arguments to replace the value of entry with key 1 with value John in map.
  • At line 11 we are calling replace() method with 3 arguments to replace the value of entry with key 1 and value Steve with value John in the map since this key-pair matches and its gets replaced.
  • At line 15 we are calling replace() method with 3 arguments to replace the value of entry with key 1 and value John1 with value Steve in the map since this key-pair not matches so no action will be taken.
  • At line 19 we are calling replaceAll() method with 1 argument to replace the value of each entry calculated by the function passed as the argument.

Result

Initial map: {1=John, 2=Jack}
Replacing value of entry with key 1 with Steve in map: {1=John, 2=Jack}
Updated map: {1=Steve, 2=Jack}
Replacing value of entry with key 1 value Steve with John in map: {1=Steve, 2=Jack}
Updated map: {1=John, 2=Jack}
Replacing value of entry with key 1 value John1 with John in map: {1=John, 2=Jack}
Updated map: {1=John, 2=Jack}
Replacing value of all entries original value plus "Smith": {1=John, 2=Jack}
Updated map: {1=John Smith, 2=Jack Smith}

5. Example of HashMap Java

As we mentioned we will create two different HashMaps. The first HashMap will be a simple one, so it will pair a String key with a Integer value. At the second one, we want to correspond many values into one key, so the values-argument is an ArrayList.

Create a java class named HashMapTest.java and add it into a Java project. Then, paste the following code.

HashMapTest.java

package com.javacodegeeks.javabasics.hashmaptest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class HashMapTest {

    public static void main(String[] args) {

        // a simple hashMap declaration with default size and load factor
        HashMap hashMap = new HashMap();
        // hashMap with multiple values with default size and load factor
        HashMap<String, ArrayList> multiMap = new HashMap<String, ArrayList>();

        // Put elements to the hashMap
        hashMap.put("USA", new Integer(1));
        hashMap.put("UK", new Integer(2));
        hashMap.put("China",new Integer(3));

        // take a value of a specific key
        System.out.println("Simple HashMap: Key 'UK' has value = " + hashMap.get("UK"));

        // see if a specific value or key is into the hashMap
        System.out.println("Simple HashMap contains value '1' - " + hashMap.containsValue(1));
        System.out.println("Simple HashMap contains key 'Greece' - "
        + hashMap.containsKey("Greece"));

        // create an arrayList to store values
        ArrayList listOne = new ArrayList();
        listOne.add("Blue");
        listOne.add("Black");
        listOne.add("Brown");

        // create list two and store values
        ArrayList listTwo = new ArrayList();
        listTwo.add("Pink");
        listTwo.add("Purple");

        // put values into map
        multiMap.put("B color", listOne);
        multiMap.put("P color", listTwo);

        // Get a set of the entries
        Set<Entry<String, ArrayList>> setMap = multiMap.entrySet();
        // Get an iterator
        Iterator<Entry<String, ArrayList>> iteratorMap = setMap.iterator();

        System.out.println("\nHashMap with Multiple Values");
        // display all the elements
        while(iteratorMap.hasNext()) {
            Map.Entry<String, ArrayList> entry = 
            (Map.Entry<String, ArrayList>) iteratorMap.next();
            String key = entry.getKey();
            List values = entry.getValue();
            System.out.println("Key = '" + key + "' has values: " + values);
        }

    }
}

Output

Simple HashMap: Key 'UK' has value = 2
Simple HashMap contains value '1' - true
Simple HashMap contains key 'Greece' - false


HashMap with Multiple Values
Key = 'P color' has values: [Pink, Purple]
Key = 'B color' has values: [Blue, Black, Brown]

Let’s explain the above code. As you can see, put() method is called in order to add pairs of key-value in the HashMap. For multiple values, we should create an instance of an ArrayList (or a List in other occasions) and add the values in it, before putting the whole list into the HashMap. To retrieve all the elements of the HashMap we have to make a small procedure, that is based on Iterator. Firstly, we should get all the sets of pairs that are contained into the HashMap, by calling entrySet() method. Then we have to get an Iterator for the entries set, in order to loop through the entire HashMap and perform operations on each key-value pair.

Moreover, we used some other methods that the class provide us in order to handle some situations easily. In order to retrieve a single value by knowing its key, get the method is called, putting the specified key as a parameter. Also to learn about the existence of a key or a value, containsKey() and containsValue()methods are used respectively. These methods return a boolean value (true or false), in order to express if a key or a value exists in the map.

6. Different ways to iterate Java HashMap

There are many ways to iterate over HashMap in java. Let’s see each method in detail-

Iterating Map

HashMap nameMap = new HashMap();
nameMap.put(1, "John");
nameMap.put(2, "Jack");

System.out.println("Iterating by using Entry and entrySet()");

for (Map.Entry entry : nameMap.entrySet())
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

System.out.println("Iterating over keys using For-Each loop");
for (Integer key : nameMap.keySet())
    System.out.println("Key = " + key + ", Value = " + nameMap.get(key));

System.out.println("Iterating over values using For-Each loop");
for (String value : nameMap.values())
    System.out.println("Value = " + value);

System.out.println("Iterating using Iterator");
Iterator<Map.Entry> entries = nameMap.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

System.out.println("Iterating over keys and searching for values");
for (Integer key : nameMap.keySet()) {
    String value = nameMap.get(key);
    System.out.println("Key = " + key + ", Value = " + value);
}

System.out.println("Iterating by java8 foreach");
nameMap.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));

Result

Iterating by using Entry and entrySet()
Key = 1, Value = John
Key = 2, Value = Jack
Iterating over keys using For-Each loop
Key = 1, Value = John
Key = 2, Value = Jack
Iterating over values using For-Each loop
Value = John
Value = Jack
Iterating using Iterator
Key = 1, Value = John
Key = 2, Value = Jack
Iterating over keys and searching for values
Key = 1, Value = John
Key = 2, Value = Jack
Iterating by java8 foreach
Item : 1 Count : John
Item : 2 Count : Jack

Now you can see the results below, in the output of the executable:

8. Download the Source Code

This was an example of HashMap in Java.

Download
You can download the full source code of this example here: HashMap Java Example

Last updated on Jan. 17th, 2022

Katerina Zamani

Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button