HashMap in java

HashMap:

HashMap extends AbstractMap class and implements the Map interface. It contains the elements in key-value pair form. It does not maintain any order for its elements. It is not allowed duplicate keys. A HashMap can have only one null key and multiple null values.

  • No order is maintained by the HashMap class.
  • It is non-synchronized.
  • Its initial default capacity is 16.
  • Its load factor is 0.75.

HashMap class declaration:

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

Where

  • K: The type of keys maintained by the HashMap.
  • V: The type of mapped values.

HashMap class Constructors:

S.No. Constructor Description
1 HashMap() It will create a default HashMap.
2 HashMap(Map<? extends K,? extends V> m) It will create and initialize the hash map by using the elements of the given Map object m.
3 HashMap(int capacity) It will create and initialize the capacity of the hash map to the given integer value, capacity.
4 HashMap(int capacity, float loadFactor) It will create and initialize both the capacity and load factor of the hash map by using its arguments.

HashMap class Methods:

S.No. Method Description
1 void clear() It will eliminate or delete all of the mappings from this map.
2 boolean isEmpty() It will return true if this map contains no key-value mappings.
3 Object clone() It will return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
4 Set entrySet() It will return a collection view of the mappings contained in this map.
5 Set keySet() It will return a set view of the keys contained in this map.
6 V put(Object key, Object value) It will add an entry to the map.
7 void putAll(Map map) It will add the specified map to the map.
8 V putIfAbsent(K key, V value) It will add the specified value with the specified key in the map only if it is not already specified.
9 V remove(Object key) It will delete or eliminate an entry for the specified key.
10 boolean remove(Object key, Object value) It will eliminate or delete the specified values with the associated specified keys from the map.
111 V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) It will compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
12 V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) It will compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
13 V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) To compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
14 boolean containsValue(Object value) It will return true if some value equal to the value exists within the map, else return false.
15 boolean containsKey(Object key) It will return true if some key equal to the key exists within the map, else return false.
16 boolean equals(Object o) It will compare the specified Object with the Map.
17 void forEach(BiConsumer<? super K,? super V> action) It will perform the given action for each entry in the map until all entries have been processed or the action throws an exception.
18 V get(Object key) It will return the object that contains the value associated with the key.
19 V getOrDefault(Object key, V defaultValue) It will return the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
20 boolean isEmpty() It will return true if the map is empty; returns false if it contains at least one key.
21 V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) It will associate the specified key with the given non-null value if it is not already associated with a value or is associated with null.
22 V replace(K key, V value) It will replace the specified value for a specified key.
23 boolean replace(K key, V oldValue, V newValue) It will replace the old value with the new value for a specified key.
24 void replaceAll(BiFunction<? super K,? super V,? extends V> function) It will replace 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.
25 Collection<V> values() It will return a collection view of the values contained in the map.
26 int size() It will return the number of entries on the map.

HashMap example:

HashMapTest.java

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
/**
 * This class is used to show the HashMap functionality.
 * @author w3schools
 */
public class HashMapTest {
	public static void main(String args[]){
		//Create HashMap object.
		Map hashMap = new HashMap();
 
		//Add objects to the HashSet.
		hashMap.put(4, "Roxy");
		hashMap.put(2, "Sunil");
		hashMap.put(5, "Sandy");
		hashMap.put(1, "Munish");
		hashMap.put(3, "Pardeep");
 
		//Print the HashMap object.
		System.out.println("HashMap elements:");
		System.out.println(hashMap);
 
		//Get iterator
		Set set=hashMap.entrySet();  
		Iterator iterator=set.iterator();  
 
		//Print the HashMap elements using iterator.
		System.out.println("HashMap elements using iterator:");
		while(iterator.hasNext()){
		   Map.Entry mapEntry=(Map.Entry)iterator.next();  
		   System.out.println("Key: " + mapEntry.getKey() + ", " +
		   		"Value: " + mapEntry.getValue());  
		}  
	}
}

Output:

HashMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
HashMap elements using iterator:
Key: 1, Value: Munish
Key: 2, Value: Sunil
Key: 3, Value: Pardeep
Key: 4, Value: Roxy
Key: 5, Value: Sandy

Example: Different ways to insert elements:

import java.util.*;  
public class HashMapExample{  
 public static void main(String args[]){  
   HashMap<Integer,String> hm=new HashMap<Integer,String>();    
    System.out.println("The initial list of elements:: "+hm);  
      hm.put(200,"A");    
      hm.put(201,"B");    
      hm.put(202,"C");   
 
      System.out.println("After invoking the put() method:: ");  
      for(Map.Entry m:hm.entrySet()){    
       System.out.println(m.getKey()+" "+m.getValue());    
      }  
 
      hm.putIfAbsent(203, "D");  
      System.out.println("After invoking the putIfAbsent() method:: ");  
      for(Map.Entry m:hm.entrySet()){    
           System.out.println(m.getKey()+" "+m.getValue());    
          }  
      HashMap<Integer,String> map=new HashMap<Integer,String>();  
      map.put(204,"E");  
      map.putAll(hm);  
      System.out.println("After invoking the putAll() method:: ");  
      for(Map.Entry m:map.entrySet()){    
           System.out.println(m.getKey()+" "+m.getValue());    
          }  
 }  
}

Output:

Example: Different ways to remove elements:

import java.util.*;  
public class HashMapExample{  
   public static void main(String args[]) {  
    HashMap<Integer,String> map=new HashMap<Integer,String>();          
      map.put(200,"A");    
      map.put(201,"B");    
      map.put(202,"C");  
      map.put(203, "D");  
    System.out.println("The initial list of elements:: "+map);  
    //key-based removal  
    map.remove(200);  
    System.out.println("The updated list of elements:: "+map);  
    //value-based removal  
    map.remove(201);  
    System.out.println("The updated list of elements:: "+map);  
    //key-value pair based removal  
    map.remove(202, "C");  
    System.out.println("The updated list of elements:: "+map);  
   }      
}

Output:

Example: Different ways to replace elements:

import java.util.*;  
public class HashMapExample{  
 public static void main(String args[]){  
   HashMap<Integer,String> hm=new HashMap<Integer,String>();    
      hm.put(200,"A");    
      hm.put(201,"B");    
      hm.put(202,"C");   
      System.out.println("The initial list of elements::");  
     for(Map.Entry m:hm.entrySet())  
     {  
        System.out.println(m.getKey()+" "+m.getValue());   
     }  
     System.out.println("The updated list of elements::");  
     hm.replace(202, "c");  
     for(Map.Entry m:hm.entrySet())  
     {  
        System.out.println(m.getKey()+" "+m.getValue());   
     }  
     System.out.println("The updated list of elements::");  
     hm.replace(201, "B", "b");  
     for(Map.Entry m:hm.entrySet())  
     {  
        System.out.println(m.getKey()+" "+m.getValue());   
     }   
     System.out.println("The updated list of elements::");  
     hm.replaceAll((k,v) -> "a");  
     for(Map.Entry m:hm.entrySet())  
     {  
        System.out.println(m.getKey()+" "+m.getValue());   
     }  
 }  
}

Output:

Next Topic: LinkedHashMap in java with example.
Previous Topic: LinkedList in java with example.