Top 15 Examples of HashMap in java : HashMap tutorial

This tutorial explains about HashMap basics in java and features and top 15 examples.

Java ArrayList Examples

How HashMap works in java

HashMap is implementation of Map interface in java. HashMap is popular collection framework used in every day life of java developer.

HashMap is combination of key and values.

key and values should be either String,primitives or any custom object. The key stored in the HashMap is based on the hashCode computed for key value. HashMap implements Map interface and declared in java.util package

In most of the backend programming, HashMap is used to store as temporary cache for either request scope or session scope.

Important points to remember for HashMap

  • Order of keys stored in HashMap is based on hashing. Even though order is not fixed.
  • HashMap allows null keys and null values
  • HashMap is not synchronized meaning is not thread safety
  • Hashmap is fail fast meaning, if we are modifying/adding/remove any object while iteration of HashMap, it throws ConcurrentModificationException

keys stored in order of calculating the Hashing mechanism .

How to Create HashMap Object using java?

HashMap provides two varitions for creating an object

  • default constructor a
  • Parameter constructor with initialCapacity=integer number
HashMap<String,String> map=new HashMap<>();
HashMap<String,String> map1=new HashMap<>(10);

he above one of the two lines create HashMap with type string with empty constructor or constructor with integer.

This number representing initial capacity

How to add Objects to HashMap

HashMap provides put method to store the key and values in the map.

import java.util.HashMap;
import java.util.Map;

public class MapTest {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("11", "oneone");
        map.put("21", "twoone");
        map.put("31", "threeone");
        map.put("41", "fourone");
        map.put("42", "fourone");

        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + " = " + value);



Important points

  • Key does not allow duplicates
  • value allows duplicates
  • It allows one null key and multiple null values

How to iterate through values HashMap?

HashMap provides values() method to iterate all the values

Collection collection=map.values();  
 for(String str:collection){  
  System.out.print(" "+str);  
```values() return the collection object which we can used in for each loop to return the each object  
out put is  
twoone fourone threeone oneone

How to Find out the size of hashmap

size() method is used to find out the size of the Hashmap


return the size as 4 for the above map.

How to Check if key object exists in HashMap

To check if specific key exist in HashMap, we have to use containsKey(Object obj) of HashMap.

if the key is found in the map, it returns true, other wise it returns false .

map.containsKey("11") //return true  
map.containsKey("134") //return false  

Check if value object available in HashMap

To check if specific value exist in HashMap, we have to use containsValue(Object obj) of HashMap.

if the value is found, it returns true, other wise it returns false .

map.containsValue("oneone") //return true  
map.containsValue("cloudmap") //return false  

How to delete object from HashMap?

map provides remove method which will removes key and value from the HashMap object.

To delete object from HashMap, we have to use remove(Object key) method of HashMap and returns the value for that key

remember only key object should be passed to remove method and returns value for that key if removed, otherwise returns null.

String value=map.remove("21");  

the above key “21” is found in map,then removes that key and value pair from the map, and returns the value object.

if key is not found, then null is returned.

How to delete all the objects from the HashMap

To remove all the key and value pairs from the map, use clear() method of HashMap.


After clear() method is used, if isEmpty() is called , it returns true as all the objects has been removed.

How to Converting Map keys to Set?

To convert the HashMap keys to set, we have to use keySet which returns Set of keys

Set keys=map.keySet();  
 for(String str:keys){  
  System.out.print(" "+str);  

How to Synchronize HashMap in java

HashMap is not synchronized. meaning more than one thread modifies the state of an object. But we can make HashMap as synchronized using synchronizeMap

Map synchronizedHashMap = Collections.synchronizeMap(map);  

How to iterate hashmap with for each loop

map.entrySet() returns Set of Map.Entry<K,V> which we can use in for loop. This iterates each item and prints key and values of an HashMap.

for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + " = " + value);

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.