Top 15 Examples of HashMap in java | HashMap tutorial

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

How HashMap works in java

HashMap is the Map interface implementation in java. HashMap is a popular collection framework used in the everyday life of java developers.

HashMap contains pair 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 the key value. HashMap implements the Map interface and defines it in java.util package

In programming, HashMap is used to store as a 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 the order is not fixed.
  • HashMap allows null keys and null values
  • HashMap is not synchronized meaning is not threaded safety
  • Hashmap is fail fast meaning, if we are modifying/adding/removing 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 variations 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);

The above one of the two lines creates HashMap with type string with empty constructor or constructor with an integer.

This number represents initial capacity.

How to add Objects to HashMap

HashMap provides the 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 the 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 use for each loop to return each object
output is
```java
twoone fourone threeone oneone

How to Find out the size of the hashmap

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

map.size()

return the size as 4 for the above map.

How to Check if the key object exists in HashMap

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

if the key is found in the map, it returns true, otherwise 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, otherwise it returns false.

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

How to delete an object from HashMap?

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

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

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

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

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

if the 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 the clear() method of HashMap.

map.clear()

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. that means 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 hash map 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);

}