Java Hashmap [With Examples]

What is Java Hashmap?

The Java HashMap class implements the Map interface, which allows us to store key-value pairs with unique keys. If you try to insert the duplicate key, it will replace the associated key’s element. The key index makes it simple to conduct actions such as updating, deleting, and so on. The java.util package contains the HashMap class.

In Java, HashMap is similar to the classic Hashtable class, however, it is not synchronized. It also allows us to store null items, however, there should only be one null key. Since Java 5, it has been denoted as <HashMap K, V>, where K represents the key and V represents the value. It derives from AbstractMap and implements the Map interface.

hashmap flow

As shown in the above figure, the HashMap class extends AbstractMap class and implements the Map interface.

Java HashMap Class Declaration:

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

Parameters:

  • K: It is the type of keys maintained by this map.
  • V: It is the type of mapped values.

Points to remember:

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

Java Hashmap Example

Code 01: HashMap to store key and value pair.

import java.util.*;  
public class hashmapeg1{  
 public static void main(String args[]){  
   HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap    
   map.put(1,"Cat");  //Put elements in Map  
   map.put(2,"Dog");    
   map.put(3,"Markhor");   
   map.put(4,"Peacock");   
       
   System.out.println("Iterating Hashmap...");  
   for(Map.Entry m : map.entrySet()){    
    System.out.println(m.getKey()+" "+m.getValue());    
   }  
}  
}  

Output:

Iterating Hashmap...
1 Cat
2 Dog
3 Markhor
4 Peacock

Explanation: In this example, we store an Integer as the key and String as the value, hence the type is HashMap <Integer, String>. The entries in the map are inserted using the put() function.

To obtain the key and value components, use the getKey() and getValue() methods. The getKey() and getValue() functions are part of the Map.Entry interface. To obtain an instance of Map.Entry, we must use the Map interface’s entrySet() function.

Code 02: No Duplicate Key on HashMap. This example shows if you try to store a duplicate key with another value, it will replace the value.

import java.util.*;  
public class hashmapeg2{  
 public static void main(String args[]){  
   HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap    
   map.put(1,"Cat");  //Put elements in Map  
   map.put(2,"Dog");    
   map.put(3,"Markhor");   
   map.put(4,"Peacock");   
   map.put(1,"Leopard");
       
   System.out.println("Iterating Hashmap...");  
   for(Map.Entry m : map.entrySet()){    
    System.out.println(m.getKey()+" "+m.getValue());    
   }  
}  
}  

Output:

Iterating Hashmap...
1 Leopard
2 Dog
3 Markhor
4 Peacock

Basics Operations

The HashMap class contains a number of methods for performing various operations on hashmaps.

  1. Add elements
  2. Access elements
  3. Change or Replace elements
  4. Remove elements

Operation 01: Java Hashmap Add Elements

The put() function of the HashMap class is used to add a single element to the hashmap.

Code 03:

import java.util.*;  
public class hashmapeg3{  
 public static void main(String args[]){  
   HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap    
   
   System.out.println("Initial HashMap: " + map);
   
   map.put(1,"Cat");  //Put elements in Map  
   map.put(2,"Dog");    
   map.put(3,"Markhor");   
   map.put(4,"Peacock");   
       
   System.out.println("HashMap after put(): ");  
   for(Map.Entry m : map.entrySet()){    
    System.out.println(m.getKey()+" "+m.getValue());    
   }  
}  
}  

Output:

Initial HashMap: {}
HashMap after put(): 
1 Cat
2 Dog
3 Markhor
4 Peacock

Operation 02: Java Hashmap Access Elements

To obtain the value from the hashmap, we may utilize the get() function.

Code 04:

import java.util.*;  
public class hashmapeg3{  
 public static void main(String args[]){  
   HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap    
   map.put(1,"Cat");  //Put elements in Map  
   map.put(2,"Dog");    
   map.put(3,"Markhor");   
   map.put(4,"Peacock");   
       
   System.out.println("HashMap after put(): ");  
   for(Map.Entry m : map.entrySet()){    
    System.out.println(m.getKey()+" "+m.getValue());    
   }  
       // get() method to get value
    String value = map.get(1);
    System.out.println("Value at index 1: " + value);
}  
}  

Output:

HashMap after put(): 
1 Cat
2 Dog
3 Markhor
4 Peacock
Value at index 1: Cat

Operation 03: Java Hashmap Replace Elements

To change the value associated with a key in a hashmap, we may use the replace() function.

Code 05:

import java.util.*;  
public class hashmapeg3{  
 public static void main(String args[]){  
   HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap    
   map.put(1,"Cat");  //Put elements in Map  
   map.put(2,"Dog");    
   map.put(3,"Markhor");   
   map.put(4,"Peacock");   
       
   System.out.println("HashMap after put(): ");  
   for(Map.Entry m : map.entrySet()){    
    System.out.println(m.getKey()+" "+m.getValue());    
   }  
  // change element with key 2
    map.replace(2, "Wolf");
    System.out.println("HashMap using replace(): ");
       for(Map.Entry m : map.entrySet()){    
    System.out.println(m.getKey()+" "+m.getValue());    
   } 
}  
}  

Output:

HashMap after put(): 
1 Cat
2 Dog
3 Markhor
4 Peacock
HashMap using replace(): 
1 Cat
2 Wolf
3 Markhor
4 Peacock

Operation 04: Java Hasmap Remove Elements

The remove() function may be used to remove elements from a hashmap.

Code 06:

import java.util.*;  
public class hashmapeg3{  
 public static void main(String args[]){  
   HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap    
   map.put(1,"Cat");  //Put elements in Map  
   map.put(2,"Dog");    
   map.put(3,"Markhor");   
   map.put(4,"Peacock");   
       
   System.out.println("HashMap after put(): ");  
   for(Map.Entry m : map.entrySet()){    
    System.out.println(m.getKey()+" "+m.getValue());    
   }  
// remove element associated with key 2
    String value = map.remove(2);
    System.out.println("Removed value: " + value);

    System.out.println("Updated HashMap: ");
       for(Map.Entry m : map.entrySet()){    
    System.out.println(m.getKey()+" "+m.getValue());    
   }  
}  
}  

Output:

HashMap after put(): 
1 Cat
2 Dog
3 Markhor
4 Peacock
Removed value: Dog
Updated HashMap: 
1 Cat
3 Markhor
4 Peacock

Creating Hashmap from Treemap

We can also create a hashmap from other maps in Java.

Code 07: creating hasmap from treemap

import java.util.HashMap;
import java.util.TreeMap;

class Main {
  public static void main(String[] args) {

    // create a treemap
    TreeMap<String, Integer> map = new TreeMap<>();
    map.put("Dog",1);
    map.put("Wolf",2);
    System.out.println("TreeMap: " + map+"\n");

    // create hashmap from the treemap
    HashMap<String, Integer> map1 = new HashMap<>(map);
    map1.put("Leopard",3);
    System.out.println("HashMap: " + map1);
  }
}

Output:

TreeMap: {Dog=1, Wolf=2}

HashMap: {Dog=1, Leopard=3, Wolf=2}

Java Hashmap Methods

MethodDescription
clear()Removes all mappings from the HashMap
compute()Computes a new value for the specified key
computeIfAbsent()This computes value if a mapping for the key is not present
computeIfPresent()Computes a value for mapping if the key is present
merge()Merges the specified mapping to the HashMap
clone()Makes the copy of the HashMap
containsKey()Checks if the specified key is present in Hashmap
containsValue()Checks if Hashmap contains the specified value
size()Returns the number of items in HashMap
isEmpty()Checks if the Hashmap is empty

FAQs

Java Hashmap vs Hashtable

  • HashMap is non-synchronized. It is not thread-safe and can’t be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads.
  • HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow any null key or value.
  • HashMap is generally preferred over HashTable if thread synchronization is not needed.

Java Hashmap vs Treemap

  1. Ordering: HashMap is not ordered, while TreeMap sorts by key.
  2. Performance: If the hash function appropriately distributes the elements across the buckets, HashMap is quicker and gives average constant time performance O(1) for the fundamental operations get() and put(). It normally works as is, however collisions do occur on occasion. In this case, HashMap manages collisions by storing colliding elements in a linked list, which reduces speed by up to O(n).
  3. Null Keys and Null Values: HashMap allow you to store one null key and multiple null values. It keeps entry with a null key in index[0] of an internal bucket. HashMap also allows storing many null values. TreeMap sorts elements in natural order and doesn’t allow null keys because compareTo() method throws NullPointerException if compared with null.

Conclusion

That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. What is Treemap in Java?

Leave a Comment