Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - HashMap

As the name suggests, HashMap is a concrete implementation of Map, which follows a technique called 'Hashing'.

As we know Map stores the values in the form of Key and Value pairs. Same applies for HashMap as well.

In a HashMap, it's only the key that is calculated based on Hashing technique.

Since, the insertion is based on Hash Code, a HashMap is unsorted and unordered.


Constructors in HashMap

HashMap():  Creates a HashMap with initial capacity 16.
HashMap(int initialCapacity) :  Creates a HashMap with a custom initial capacity.
HashMap(int initialCapacity, float LoadFactor) :  Creates a HashMap with a custom initial capacity and custom Load Factor.
HashMap(Map map) :



How do we define a HashMap?

A HashMap can be defined by :


Map myHashMap = new HashMap();

or :


Map <Integer,String> myHashMap = new HashMap <Integer,String>();


We have defined the HashMap and specified the key - value pair type using the angular brackets(i.e. < >). And as we can see the key has to be of type Integer and value needs to be of type String.

The angular brackets(i.e. < >) ensures type safety and are known as Generics(We will be looking later). By imposing Generics we make sure that the key and the value must be of Integer and String type.


public class TestCollection{
  public static void main(String[] arg){

    Map <Integer,String> myHashMap = new HashMap <Integer,String> ();

     //Adding 'John' to HashMap with '1' as key.
    myHashMap.put(1,"John");

    //Adding 'Paul' to HashMap with '2' as key.
    myHashMap.put(2,"Paul");

    //Adding 'Tom' to HashMap with '1' as key,
    //replaces 'John' with 'Tom'.
    myHashMap.put(1,"Tom");

    //Used to get the value for key '1'.
    String value = myHashMap.get(1);

    System.out.println("Value for key 1 is : "+value);

    // Deletes "Tom" from the HashMap.
    myHashMap.remove(1);

    if(myHashMap.containsKey(2)){

     System.out.println("Paul is present in the HashMap.");
    }
  }
}

Output :


   Value for key 1 is : Tom
   Paul is present in the HashMap.

1. We have created a HashMap() using the below format.


Map <Integer,String> myHashMap = new HashMap <Integer,String> ();

2. Then, we have added 'John' to the HashMap, with '1' as the Key.


myHashMap.put(1,"John");

Key Value
1 John

3. Next, we have added 'Paul' to the HashMap, with '2' as the Key.


myHashMap.put(2,"Paul");

Key Value
1 John
2 Paul

4. After that, we have added 'Tom' to the HashMap with '1' as key again.


myHashMap.put(1,"Tom");

And guess what happened? 'John' gets replaced with 'Tom'.


Key Value
1 Tom
2 Paul

Note : We have also seen put() returns an Object. It is nothing but the old value which is replaced. i.e. 'John' in this case. And if no value is replaced, it returns null.


5. Now, if we want to get the value for the 'key' 1, we have used the get() method.


String value = myHashMap.get(1);

The value is 'Tom' for key '1'.

6. Next, we tried to remove an Entry from the HashMap. And we have done using the remove() method.


myHashMap.remove(1);

Key Value
2 Paul

7. Then we tried to check if the key '2' is present in the HashMap or not.


if(myHashMap.containsKey(2)){
   System.out.println("Paul is present in the HashMap.");
}

How to Iterate a HashMap/Map?

Let us add a few values to a HashMap and see how do we fetch them.


public class TestCollection{
  public static void main(String[] arg){

    Map <Integer,String> myHashMap = new HashMap <Integer,String> ();

    myHashMap.put(1,"John");
    myHashMap.put(2,"Paul");
    myHashMap.put(3,"Tom");

    for(Map.Entry entry: myHashMap.entrySet()) {

     System.out.println("The key is : "+entry.getKey()+"
            and the value is : "+entry.getValue());

    }
  }
}

Output :


   The key is : 1 and the value is : John
   The key is : 3 and the value is : Tom
   The key is : 2 and the value is : Paul

In the above code, after we have added three Entries(i.e. Key and Value Pair) to the HashMap. We have used the for each loop to iterate the Entries of the Map.


for(Map.Entry entry: myHashMap.entrySet()) {

   System.out.println("The key is : "+entry.getKey()+"
          and the value is : "+entry.getValue());

  }

A Key - Value pair in a map is called as an Entry. So, in the 'Map' interface there is an 'Entry' interface.

And 'Map.Entry' type object actually holds a key - value pair or an Entry.

So, to fill this 'Map.Entry entry', we need a Set of HashMaps in the form of Key - Value pairs.

Now, 'myHashMap.entrySet()' solves this purpose. 'entrySet()' method returns a Set of key and values from the HashMap.


for(Map.Entry entry: myHashMap.entrySet())

Now, 'myHashMap.entrySet()' solves this purpose. 'entrySet()' method returns a Set of key and values from the HashMap.

So, when we get the key - value pair in the 'entry' object of 'Map.Entry'. We can get the key using 'entry.getKey()' and value using 'entry.getValue()'.


System.out.println("The key is : "+entry.getKey()+" and the value is : "+entry.getValue());

If we look at the output, the order is not maintained. Because the insertion is based on HashCode of the key.


Advantages and disadvantages of HashMap

  1. The methods in a HashMap are not Synchronized.

  2. HashMap is not Thread safe.

  3. Since it operates using Multithreading it is quite faster.

  4. It allows one null as key and value as well.