HashMap in Java

Java HashMap class implements the Map interface which lets us store the key and value pair. In this case, the keys should be unique, any kind of duplication will result in the replacement of the corresponding key.

This concept has been a part of Java’s collection since Java 1.2. The java.util package contains the HashMap<K,V> class. Accessing the keys takes place using its indices.

The concept of HashMap is a bit alike the HashTable. The only difference is that the HashMap is not synchronized. We can also store null keys, but the null key object should be only one whereas, the null values can be many.

Declaration of a HashMap in Java:

This is how we declare java.Util.HashMap class

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

Parameters of a HashMap Class:

The java.util.HashMap class takes a couple of parameters as follows:

  •  K: The key type that the map contains
  •  V: The type of the mapped values

Constructors of Java HashMap class:

Constructor Description
HashMap() This method allows us to create a default HashMap
HashMap(Map < ?  extends K, ? extends V> m) It lets us initialize the HashMap with the elements of the Map object m.
HashMap(int capacity) It initializes the hash map’s capacity to the given integer value
HashMap(int capacity, float loadFactor) It initializes the capacity and the load factor of the hashmap with the help of its arguments.

 Methods of Java HashMap class:

Method Description
void clear() It clears all the present mappings.
boolean isEmpty() It returns a boolean value. It returns true if the map has no key values and returns false otherwise.
boolean containsValue(Object value) It returns a boolean value. It returns true if the same value already exists within the map and returns a false otherwise.
boolean containKey(Object key) It returns a boolean value. It returns the true same key already exists within the map and returns false otherwise.
boolean equals(Object o) It compares the given object with the Map.
Collection<V> values() It returns a collection view of the values in the Map.
int size() It returns the number of entries present in the map.
Object clone() It returns the keys and values that are not cloned.
Set entrySet() It returns a collection view of the mappings present in the map. 
Set keySet() It returns the set view of the keys present in the map.
void remove(Object key) It deletes an entry of the particular key.
boolean remove(Object key, Object value) It removes the particular values with the associated keys in the map. 
void get(Object key) It returns the object that contains the value of the key
void getOrDefault(Object key, void defaultValue) It returns the value to the mapped key or to the default key if no mapping has taken place.
void put(Object key, Object value) It inserts an entry in the map.
void putAll(Map map) It inserts the specified map inside the map.
void putAbsent(K key, V value) It inserts the specified value with the particular key in the map only if it is not yet mentioned
void compute(K key, BiFunction<? super K, super V,? extends V> remappingFunction) It computes a mapping for the specified key and the mapped value. It returns null if there is no mapping.
void computeIfAbsent(K key, Function<? super K, extends V> mappingFunction) It computes the value using the given mapping function if the key is not already associated with the value. It returns into the map if it is not null.
void computePresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunctions) It computes a new mapping given the key and its mapped value if the key is present and is non-null.
void forEach(BiConsumer<? super K,? super V> action) It performs the action for every entry in the map till all the entries are processed or an exception is thrown.
void merge(K key, V value, BiFunction<? super V, ? super V,? extends V> remappingFunction) If the mentioned key has no associated value or null, it associates the key with the given value.
void replace(K key, V value) It replaces the given key for the mentioned key.
boolean replace(K key, V oldVale, V newValue)  It replaces the old value with the given new value.
void replaceAll(BiFunction<? super K, super V,? extends V> function) It replaces the value of each entry by invoking the function on that entry.

Java HashMap Sample Program:

import java.util.*; 
public class DFHashMap1{  
 public static void main(String args[]){    
HashMap<Integer,String> map=new HashMap<Integer,String>(); //HashMap creation    
map.put(1,"Java"); 
//Adding elements to Map   
map.put(2,"Python");    
map.put(3,"C");   
map.put(4,"C++");   
System.out.println("Hashmap Iteration takes place");  
   for(Map.Entry m : map.entrySet()){    
System.out.println(m.getKey()+" "+m.getValue());    
   }  
}  
}  

Output:
Hashmap Iteration takes place
1 Java
2 Python
3 C
4 C++

No Duplicate Key on HashMap:

import java.util.*; 
public class DFHashMap2{  
 public static void main(String args[]){  
  
HashMap<Integer,String> map=new HashMap<Integer,String>(); //HashMap creation    
  
map.put(1,"Java"); 
//Put elements in Map  
  
map.put(2,"Python");    
  
map.put(3,"C");   
  
map.put(1,"C++"); // duplication of key
         
System.out.println("Hashmap iteration takes place");  
   for(Map.Entry m : map.entrySet()){    
   
System.out.println(m.getKey()+" "+m.getValue());    
   }  
}  
}  

Output:
Hashmap Iteration takes place
1 Java
2 Python
3 C
4 C++

Java HashMap Sample to implement add() method:

import java.util.*; 
class DFHashMap3{ 
 public static void main(String args[]){  
  
HashMap<Integer,String> h=new HashMap<Integer,String>();    
   
System.out.println("Initial set of values: "+h);  
     
h.put(100,"Java");    
     
h.put(101,"Python");    
     
h.put(102,"C++");   
            
System.out.println("After invoking put() method ");  
     
for(Map.Entry m:h.entrySet()){    
      
System.out.println(m.getKey()+" "+m.getValue());    
      }        
     
h.putIfAbsent(103, "CSS"); 
     
System.out.println("After invoking putIfAbsent() method ");  
     
for(Map.Entry m:h.entrySet()){    
          
System.out.println(m.getKey()+" "+m.getValue());    
    }  
     
HashMap<Integer,String> map=new HashMap<Integer,String>();  
      map.put(104,"JavaScript");  
     
map.putAll(h);  
     
System.out.println("After invoking putAll() method ");  
     
for(Map.Entry m:map.entrySet()){   
          
System.out.println(m.getKey()+" "+m.getValue());    
          }  
 }  
}  

Output:

Initial set of values: {}
After invoking put() method
100 Java
101 Python
102 C++
After invoking putIfAbsent() method
100 Java
101 Python
102 C++
103 CSS
After invoking putAll() method
100 Java
101 Python
102 C++
103 CSS
104 JavaScript

Java HashMap Sample to implement remove() method:

import java.util.*; 
public class DFHashMap4 {  
   public static void main(String args[]) {  
   
HashMap<Integer,String> map=new HashMap<Integer,String>();         
     
map.put(100,"Java");    
    
map.put(101,"Python");   
    
map.put(102,"C++");  
    
map.put(103, "JavaScript"); 
  
System.out.println("Initial set of values: "+map);  
   
map.remove(100);  
   
System.out.println("Updated set of values: "+map);  
   
map.remove(101);  
   
System.out.println("Updated set of values: "+map);  
    map.remove(102, "C++");  
   
System.out.println("Updated set of values: "+map);  
   }      
}

Output:
Initial set of values: {100=Java, 101=Python, 102=C++, 103=JavaScript}
Updated set of values: {101=Python, 102=C++, 103=JavaScript}
Updated set of values: {102=C++, 103=JavaScript}
Updated set of values: {103=JavaScript}

Java HashMap sample to implement replace() method:

import java.util.*; 
class DFHashMap5{ 
 public static void main(String args[]){  
  
HashMap<Integer,String> h=new HashMap<Integer,String>();    
     
h.put(100,"Java");    
     
h.put(101,"Python");    
     
h.put(102,"C++");   
     
System.out.println("Initial set of values:");  
    
for(Map.Entry m:h.entrySet())  
     {  
        System.out.println(m.getKey()+" "+m.getValue());   
     }  
    
System.out.println("Updated set of values:");  
    
h.replace(102, "HTML"); 
    
for(Map.Entry m:h.entrySet())  
     {  
       
System.out.println(m.getKey()+" "+m.getValue());   
     }  
    
System.out.println("Updated set of values:");  
    
h.replace(101, "HTML", "JavaScript");  
    
for(Map.Entry m:h.entrySet())  
    {  
       
System.out.println(m.getKey()+" "+m.getValue());   
     }   
    
System.out.println("Updated set of values:");  
    
h.replaceAll((k,v) -> "ReactJS");  
    
for(Map.Entry m:h.entrySet())  
     {  
       
System.out.println(m.getKey()+" "+m.getValue());   
     }  
 }  
}

Output:

Initial set of values:
100 Java
101 Python
102 C++

Updated set of values:
100 Java
101 HTML
102 C++

Updated set of values:
100 Java
101 JavaScript
102 C++

Updated list of elements:
100 ReactJS
101 ReactJS
102 ReactJS

Difference between HashSet and HashMap in Java:

The main difference between HashSet and HashMap is that the former contains only values whereas, the latter consists of values and keys.

Features of a HashMap in Java

Before getting to know about the various features that HashMap provides, let us see what hashing is. Hashing is a technique by which we can convert a large String to a smaller String. It represents the same String but with a shorter value as it is useful in indexing and performing quicker searches. A HashMap uses this hashing technique.

Here are a few features of HashMap:

  • It is present in the java.util.package.
  • It implements a Cloneable and Serializable interface.
  • It does not allow duplication of keys but also duplication of values. This means, a single key cannot contain multiple values, but more than one key can contain the same value.
  • HashMap allows a null key for once and multiple values.
  • It extends the abstract class AbstractMap which provides an unfinished implementation of the Map interface.
  • It provides no guarantee that the order of the map will remain constant.

Internal structure of a HashMap:

Internally, a HashMap consists of an array of Node and a node that is given as a class with four fields. These four fields include:
1. int hash
2. K key
3. V value
4. Node next
As the node has a reference to its own object, it is a linked list.

Performance of Java HashMap:

A couple of factors determine the performance of a HashMap. These two factors are:
1. Initial Capacity
2. Load Factor

1. Initial Capacity

It is the HashMap’s capacity during the time of its creation. It denotes the number of buckets a HashMap can hold when it is created. In java, a HashMap can initially hold 16 key value pairs, that is, 2^4.

2. Load Factor

It is the percent value of the capacity after which the capacity of HashMap will be increased. In the default manner, the rehearsing takes place after filling 75% of the capacity.

The other two factors are:

3. Threshold

Threshold is the product of the Load Factor and Initial Capacity. By default, it is (16 * 0.75 = 12). Rehashing takes place once the insertion of 12 key-value pairs into the HashMap.

4. Rehashing

This process doubles the capacity of the HashMap once it reaches the Threshold. It HashMap continues to rehash in the sequence – 2^4, 2^5, 2^6, 2^7, and so on.

Synchronized HashMap:

The HashMap is unsynchronized. This means it has various threads accessing it simultaneously. When this takes place, at least a single thread manipulates the HashMap structurally to synchronize it externally. This process is done by synchronizing some object that encapsulates the HashMap.

For example:

Map m = Collections.synchronizedMap(new HashMap(…));

Here, Map m is synchronized. In the event of any structure modification, the iterators in this class would fail. The only way to avoid this is by implementing the iterator’s remove method. In this case, it throws ConcurrentModificationException.

The time complexity of HashMap:

The time complexity that HashMap provides is constant for basic operations like get, and put. Iteration using HashMap varies according to its capacity and the count of key-value pairs. Most often, the iteration is directly proportional to the sum of capacity and size. Capacity is based on the number of buckets in HashMap. Therefore, it is not advisable to hold many buckets in HashMap.

Conclusion:

This is all about HashMap in Java. you can try the sample program provided in this article to know how this concept is being implemented.

Leave a Reply

Your email address will not be published. Required fields are marked *