HashMap in Java | Methods, Use, Example

HashMap in Java is an unordered collection that stores elements (objects) in the form of key-value pairs (called entries).

It is expressed as HashMap<Key, Value>, or HashMap<K, V>, where K stands for key and V for value. Both Key and value are objects. HashMap uses an object to retrieve another object.

If the key is provided, its associated value can be easily retrieved from the HashMap. Keys in the map must be unique which means we cannot use duplicate data for keys in the HashMap.

If we try to insert an entry that has a duplicate key, the map replaces the old entry with a new entry.

Java HashMap class is one of four concrete implementations of the Map interface. It was added in Java 1.2 version. It is found in the java. util.HashMap<K, V> package. It is efficient for locating a value, adding an entry, and deleting an entry.

Hierarchy of HashMap class in Java


HashMap class in Java extends AbstractMap class and implements the Map interface. The hierarchy diagram of HashMap can be seen in the below figure.Java HashMap hierarchy diagram

 

HashMap class Declaration


HashMap is a generic class that can be declared as follows:

public class HashMap<K,V>
   extends AbstractMap<K,V>
   implements Map<K,V>, Cloneable, Serializable

Features of Java HashMap class


There are several features of HashMap class that need to keep in mind. They are as:

1. The underlying data structure of HashMap is HashTable. In simple words, HashMap internally uses hash table for storing entries. That means accessing and adding an entry almost as fast as accessing an array.

2. In HashMap, insertion order is not preserved (i.e. maintains no order). That means we cannot retrieve keys and values in the same order in which they have been inserted into the HashMap.

3. It is based on the Hashcode of keys, not on the hash code of values.

4. Java HashMap contains only unique keys that means no duplicate keys are allowed but values can be duplicated. We retrieve values based on the key.

5. Heterogeneous objects are allowed for both keys and values.

6. Java HashMap can have only one null key because duplicate keys are not allowed.

7. Multiple null values are allowed in the HashMap.

8. HashMap in Java is not synchronized that means while using multiple threads on the HashMap object, we will get unreliable results.


9. Java HashMap implements Cloneable, and Serializable interfaces but not implements Random Access.

10. HashMap is the best choice if our frequent operation is a search operation.

11. If no element exists in the HashMap, it will throw an exception named NoSuchElementException.

12. Java HashMap stores only object references. Therefore, we cannot use primitive data types like double or int. We can use wrapper class like Integer or Double instead.

Constructors of HashMap class


HashMap class in Java provides four constructors that are as follows:

1. HashMap(): It is used to construct an empty HashMap object with the default initial capacity of 16 and the default fill ratio (load factor) is 0.75. The syntax to create a hash map object is as follows:

HashMap hmap = new HashMap();
HashMap<K, V> hmap = new HashMap<K,V>(); // Generic form.

2. HashMap(int initialCapacity): It is used to create an empty hash map object with a specified initial capacity under the default load factor 0.75. The general syntax is as follows:

HashMap<K,V> hmap = new HashMap<K,V>(int initialCapacity);

3. HashMap(Map m): This constructor is used to create hash map object by initializing the elements of the given Map object m.

4. HashMap(int initialCapacity, float loadFactor): This constructor is used to create hash map object with specified initial capacity and load factor.

The general syntax to create hash map object with initial capacity and load factor is as:

HashMap<K,V> hmap = new HashMap<>(int initialCapacity, float loadFactor);

For example:
      HashMap<String, Integer> hmap = new HashMap<>(30, 0.7f);

In the above syntax, capacity is the number of buckets in which hash map values can be stored. The load factor is the amount of buckets that are used before the capacity automatically is grown.

The value is a floating-point number that has ranges from 0 (empty) to 1.0 (full). 0.7 means when buckets are 70% full, the capacity is increased. The default capacity is 16 and the load factor is 0.75 that is often sufficient.

HashMap Methods in Java


In this section, we have listed several important methods available in HashMap class that are as follows:

1. void clear(): It is used to remove entries from the specified map.

2. boolean isEmpty(): This method is used to check whether the map is empty or not. If there are no key-value mapping present in the hash map then it returns true, else false.

3. Object clone(): It is used to create a shallow copy of this HashMap. Only hashmap and all entries are cloned, not elements. Both this map and new map share references to the same keys and values.


4. Set entrySet(): It is used to return a set view containing all of the key/value pairs in this map.

5. Set keySet(): This method is used to retrieve a set view of the keys in this map.

6. V put(Object key, Object value): This method is used to insert an entry in the map.

7. void putAll(Map map): This method is used to insert all the entries of the specified map to another map.

8. V putIfAbsent(K key, V value): This method adds the specified value associated with the specified key in the map only if it is not already specified.

9. V remove(Object key): This method is used to delete an entry for the specified key.

10. boolean remove(Object key, Object value): This method removes the specified value associated with specific key from the map.

11. int size(): This method returns the number of entries in the map.

12. Collection values(): This method returns a collection view containing all of the values in the map.

13. V get(Object key): This method is used to retrieve the value associated with a key. Its return type is Object.

14. V replace(K key, V value): This method is used to replace the specified value for a specified key.

15. boolean replace(K key, V oldValue, V newValue): This method is used to replace the old value with the new value for a specified key.

16. boolean containsValue(Object v): This method is used to determine if map contains a particular value. It returns true if some value is equal to the v.

17. boolean containsKey(Object k): This method is used to determine if the map contains a particular key. It will return true if some key in this map is equal to k.

18. boolean equals(Object o): This method is used to compare the specified Object with the Map.

Java HashMap Example Programs


1. Let’s create a program where we will simply add entries in the HashMap and display it on the console.

Program source code 1:

import java.util.HashMap;
public class HashMapEx1 {
public static void main(String[] args) 
{
// Create a HashMap.	
  HashMap<String,Integer> hmap = new HashMap<>();
 
// Checking HashMap is empty or not.
   boolean empty = hmap.isEmpty();
   System.out.println("Is HashMap empty: " +empty);
 
// Adding entries in the hash map.
   hmap.put("John", 24); // hmap.size() is 1.
   hmap.put("Deep", 22); // hmap.size() is 2.
   hmap.put("Shubh", 15); // hmap.size() is 3.
   hmap.put("Riky", 22); // hmap.size() is 4. // Adding duplicate value.
   hmap.put("Mark", 30); // hmap.size() is 5.
   
System.out.println("Entries in HashMap: " +hmap);  
int size = hmap.size();
System.out.println("Size of HashMap: " +size);

// Adding null key and value.
   hmap.put(null, null); // hmap.size() is 6.
   System.out.println("Updated entries in HashMap: " +hmap);
   }
}
Output:
      Is HashMap empty: true
      Entries in HashMap: {Riky=22, Shubh=15, John=24, Mark=30, Deep=22}
      Size of HashMap: 5
      Updated entries in HashMap: {null=null, Riky=22, Shubh=15, John=24, Mark=30, Deep=22}

As you can see from the above output, the entries in the HashMap are in no particular order in which they are inserted in map. We have stored String as keys, and Integer as values as so we are using HashMap<String, Integer> as the type. The put() method adds the entries to the map.

2. Let’s take an example program in which we will try to add duplicate keys and values in HashMap.

Program source code 2:

import java.util.HashMap;
public class HashMapEx2 {
public static void main(String[] args) 
{	
 HashMap<Integer, String> hmap = new HashMap<>();
   
 hmap.put(5, "Banana");
 hmap.put(10, "Mango");
 hmap.put(15, "Apple");
System.out.println("Entries in HashMap: " +hmap);  
System.out.println("Size of HashMap: " +hmap.size());

// Adding duplicate key in hash map.
   hmap.put(10, "Guava"); // Still hmap.size is 3.
   hmap.put(20, "Banana"); // Adding duplicate value.
   System.out.println("Updated entries in HashMap: " +hmap);
   System.out.println("Size after adding duplicate value: " +hmap.size());
   }
}
Output:
      Entries in HashMap: {5=Banana, 10=Mango, 15=Apple}
      Size of HashMap: 3
      Updated entries in HashMap: {20=Banana, 5=Banana, 10=Guava, 15=Apple}
      Size after adding duplicate value: 4

As you can see in this program, we cannot store duplicate keys in HashMap. However, we have tried to store a duplicate key with another value, but it simply replaced the value.

3. Let’s create a program where we will perform remove operation. We will remove entry from the HashMap using remove() method. Look at the source code.

Program source code 3:

import java.util.HashMap;
public class HashMapEx3 {
public static void main(String[] args) 
{	
 HashMap<Character,String> hmap = new HashMap<>();
   
 hmap.put('R', "Red");
 hmap.put('O', "Orange");
 hmap.put('G', "Green");
 hmap.put('B', "Brown");
 hmap.put('W', "White");

// Displaying HashMap entries.  
   System.out.println("Entries in HashMap: " +hmap);

// Removing Key-Value pairs for key 'B'. 
  Object removeEntry = hmap.remove('B');
  System.out.println("Removed Entry: " +removeEntry);
  System.out.println("HashMap Entries after remove: " +hmap);
  
// Checking entry is removed or not.  
  Object removeEntry2 = hmap.remove('W', "White");
  System.out.println("Is entry removed: " +removeEntry2);
  System.out.println("Updated HashMap entries: " +hmap);
   }
}
Output:
       Entries in HashMap: {R=Red, B=Brown, G=Green, W=White, O=Orange}
       Removed Entry: Brown
       HashMap Entries after remove: {R=Red, G=Green, W=White, O=Orange}
       Is entry removed: true
       Updated HashMap entries: {R=Red, G=Green, O=Orange}

4. Let’s take an example program where we will replace a specified value for the specified key. Look at the source code.

Program source code 4:

import java.util.HashMap;
public class HashMapEx4 {
public static void main(String[] args) 
{	
 HashMap<Character,String> hmap = new HashMap<>();
   
 hmap.put('R', "Red");
 hmap.put('O', "Orange");
 hmap.put('G', "Green");
 hmap.put('B', "Brown");
 hmap.put('W', "White");

// Displaying HashMap entries.  
   System.out.println("Entries in HashMap: " +hmap);

// Replacing specified value for the specified key.  
   Object replaceValue = hmap.replace('B', "Black");
   System.out.println("Replaced value: " +replaceValue);
   System.out.println("Updated entries in HashMap: " +hmap);
   
  boolean replaceValue2 = hmap.replace('G', "Green", "Greenish");
  System.out.println("Is value replaced: " +replaceValue2);
  System.out.println(hmap);
   }
}
Output:
       Entries in HashMap: {R=Red, B=Brown, G=Green, W=White, O=Orange}
       Replaced value: Brown
       Updated entries in HashMap: {R=Red, B=Black, G=Green, W=White, O=Orange}
       Is value replaced: true
       {R=Red, B=Black, G=Greenish, W=White, O=Orange}

Use of HashMap in Java


Java HashMap can be the best choice if we want to perform a search operation. It is designed to rapidly find things. The best example of this kind is phonebook. A name of person (a string) can be used to search the person’s phone number.

Let’s understand it with a simple example program. Look at the following source code.

Program source code 5:

import java.util.HashMap;
public class HashMapUse {
public static void main(String[] args) 
{	
 HashMap<String, Long> hmap = new HashMap<>();
   
 hmap.put("John", 9431676282L);
 hmap.put("Deep", 8292736478L);
 hmap.put("Shubh", 8123543268L);
 hmap.put("Mark", 9876789142L);
 hmap.put("Ricky", 8768976872L);

// Retrieve number with its key by calling get() method.
   Long number = hmap.get("Deep");
   System.out.println("Deep's phone number: " +number);
   
   Long number2 = hmap.getOrDefault("Steave", -1L);
   System.out.println("Alex's phone number: " +number2);
   }
}
Output:
      Deep's phone number: 8292736478
      Alex's phone number: -1

In this example, we have created a HashMap called phonebook with keys (person’s name) that are strings and values (person’s phone number) that are Long objects. Objects are stored in the hash map by calling put(Object key, Object value) method.

This method stores an item on the map with key as name and value as a phone number. hmap.put(“John”, 9431676282L);. If the specified key is not found, -1 is returned by default.

Hope that this tutorial has covered the basic important points related to HashMap in Java with example programs. I hope that you will have understood this topic.
Thanks for reading!!!