Skip to main content

HashMap in Java

HashMap in Java

In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.

What is HashMap in java?

Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework.

Time complexity of HashMap in Java? :

Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost.

Internal working of HashMap in java

HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of nodes wherein each node contains key-value pairs. HashMap in Java works on the principle of hashing, where hashing is used to calculate the index of the bucket.
To store and retrieve any key-value pair, hashing method applied onto the key object to calculate the index of the bucket.
Read this article, to know more about the Internal working of HashMap in java.

Important point to remember about the HashMap in java?

  • A primitive type cannot be a key or a value of the HashMap.
  • Only one null allowed as the key and multiple null are allowed as the value object.
  • The key must be unique within a HashMap i.e., duplicity of keys are not allowed
  • HashMap store key-value pair into the indexed bucket (index calculate using the hashing technique), so insertion order is not maintained.
  • HashMap in Java is not synchronized among the multiple threads, so we need to make it synchronized by ourselves.
  • HashMap is marked with two Marker interfaces those are Cloneable and Serializeable. (we are going to discuss this later in the post)

Hierarchy of the HashMap in java?

Look at this diagram, to understand the hierarchy of the HashMap.
Declaration of HashMap
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
     ----------------
}
The abstract class , i.e., AbstractMap<K,V>, provides a basic and abstract implementation of the Map Interface to the HashMap.

Why Cloneable?

Cloneable is a marker interface and it is a part of java.lang package. A class implements this interface if that class wants to call the clone() method of Object class using super keyword i.e., super.clone(); through any method or any constructor. If that class does not implement this marker interface and invoke the i.e., super.clone(); then java.lang.CloneNotSupportedException will be raised.
HashMap in Java, provides overrode clone() method that internally calls the actual clone() method of Object class. So, HashMap needs to implement this marker interface.
Note : The clone() method of Object class is used to create a cloned object.

Why Serializable?

Serializable is a marker interface and it is a part of java.io package. If Any class implements this interface then the class can be serialized or deserialized. Serialization is a process in which an object is converted into the byte stream and Deserialization is the reverse of serialization i.e., byte stream to java object. Serialization helps us to store and retrieve objects from and to files, databases, networks, etc. The only class marked with the Serializable interface can be serialized or deserialized.
HashMap in Java often needs to store and retrieve the object from the files, databases, etc. That's why HashMap is implemented as Serializable.

How to create object of HashMap in java?

Till now, we have learned what is HashMap in Java and its hierarchy, now let's have a look at the different ways to create objects of HashMap.

Default Constructor :

HashMap<String, Integer> hashMap = new HashMap<>();
With the help of new keyword and default constructor i.e., HashMap<>() , we can instantiate the HashMap. Here, as we can see HashMap is attatched with String and Integer on the left side of '=' operator, which is used to declare the type of key and value here String will be the type of Key and Integer will be the type of Value.

Using Constructor which require another Map :

A HashMap in Java can be created from another map, in that case, all entry of one map is copied into another map.
HashMap<String, Integer> firstHashMap = new HashMap<>();
firstHashMap.put("one" , 1);
firstHashMap.put("two" , 2);
firstHashMap.put("three" , 3);
firstHashMap.put("four" , 4);
HashMap<String, Integer> secondHashMap = new HashMap<>(firstHashMap);
System.out.println(secondHashMap);
Output
{two=2, three=3, four=4, one=1}

How to add key-value pairs into the HashMap in java?

HashMap provides various methods to add key-value pairs, lets look at them one-by-one.

Using put() method

The put() method is used to add key-value pair into the HashMap. This method takes 2 argument, first is key and second is value.

Java HashMap Example 1 : Using put() method of HashMap, to store Price of the Book w.r.t. to Name of the book

HashMap<String, Integer> bookNameWithPrice = new HashMap<>();
bookNameWithPrice.put("Programming In Java", 450);
bookNameWithPrice.put("Introduction to Algorithms", 800);
bookNameWithPrice.put("Data Structures", 600);
bookNameWithPrice.put("Programming In C" , 350);
System.out.println(bookNameWithPrice);
Output
{Programming In Java=450, Programming In C=350, Introduction to Algorithms=800, Data Structures=600}
In the above example, we create a HashMap that takes the name of the book as the key and its price as value.

Using putIfAbsent() method

The putIfAbsent() method is also used to add key-value pair into the HashMap but only if the provided key is not already exisis within the HashMap. This method also takes 2 argument, first is key and second is value.

Java HashMap Example 2 : Add key-value in the above created HashMap Using putIfAbsent() method.

bookNameWithPrice.putIfAbsent("Programming In Java", 550);  // Won't work as "Programming In Java" already in the HashMap
bookNameWithPrice.putIfAbsent("Computer Networks", 350);
System.out.println(bookNameWithPrice);
Output
{Computer Networks=350, Programming In Java=450, Programming In C=350, Introduction to Algorithms=800, Data Structures=600}
As we can see, the price of "Programming In Java" is not updated, but a new book named as "Computer Networks" is added to the HashMap in Java.

Using putAll(map) method

The putAll(map) method takes an argument of Map type and used to add all the key-value pair from the argument map into the HashMap.

Java HashMap Example 3 : Add All the key-value pairs of above created hashmap : "bookNameWithPrice" into a new HashMap using putAll() method.

HashMap<String, Integer> copiedHashMap = new HashMap<>();
copiedHashMap.putAll(bookNameWithPrice);
System.out.println("Previous HashMap : " + bookNameWithPrice);
System.out.println("--------------------------------------");
System.out.println("New HashMap : " + copiedHashMap);
Output
Previous HashMap : {Computer Networks=350, Programming In Java=450, Programming In C=350, Introduction to Algorithms=800, Data Structures=600}
--------------------------------------
New HashMap : {Computer Networks=350, Programming In Java=450, Programming In C=350, Introduction to Algorithms=800, Data Structures=600}

How to iterate over the HashMap in java?

This is also very important to understand how we can iterate over the hashmap in java. Let's look at an example

Java HashMap Example 4 : Using forEach() method of HashMap, to print all the data of HashMap (bookNameWithPrice)

bookNameWithPrice.forEach( 
     (key,value) -> System.out.println("Book -> Name : " + key + ", Price : " + value)
);
Note : Addition or Deletion of any key-value pair is not accepted while iterating over the HashMap in Java. In such case, java.util.ConcurrentModificationException is raised.

Output
Book -> Name : Programming In Java, Price : 450
Book -> Name : Programming In C, Price : 350
Book -> Name : Introduction to Algorithms, Price : 800
Book -> Name : Data Structures, Price : 600
Book -> Name : Computer Networks, Price : 350

Java HashMap Example 5 : Iterate over the HashMap to create a list of Book class using forEach()

Lets first implement the structure of Book Class
class Book{
     private String name;
     private Integer price;

     public Book(String name, Integer price){
          this.name = name;
          this.price = price;
     }

     @Override
     public String toString(){  
          return "[ " + name + " : " + price + " ]";
     }   
}
Create a list while iterating over the HashMap
List<Book> listOfBooks = new ArrayList<>();

bookNameWithPrice.forEach( 
     (key,value) -> { 
          Book book = new Book(key, value);
          listOfBook.add(book);
     }
);

for(Book book : listOfBooks){
     System.out.println(book);    // Internally toString() method of Book class will be called
}
Output
[ Programming In Java : 450 ]
[ Programming In : 350 ]
[ Introduction to Algorithms : 800 ]
[ Data Structures : 600 ]
[ Computer Networks : 350]
There are various ways to iterate over the hashmap in java. Read this article, to know more about How to iterate HashMap in Java.

How to get the data from the HashMap in java?

In the previous section, we learned how to iterate over the HashMap in Java, but what would happen if anyone wants to get any particular value. In that case, we must have the key of that particular value, by using that key we can easily get the value from the HashMap in Java. To do this, HashMap provides few methods to get the value from the HashMap in Java.

Using get() method

The get() method is used to get the value by key, it takes the key object and returns the value mapped with that key within the HashMap.
HashMap.get() method
V value = hashMap.get(k) // Here k is the Key

Java HashMap Example 6 : Using get() method of HashMap, get the Price of the Book named with "Programming In Java" from the HashMap

Integer price = bookNameWithPrice.get("Programming In Java");
System.out.println("Price of the Book named with Programming In Java : " + price);
Output
Price of the Book named with Programming In Java : 450
Note : If the key is not found in the HashMap then the null value is returned by the HashMap in Java.

Using getOrDefault() method

The getOrDefault() method works as same as get() method, but it takes one more argument. If the key is not found in the HashMap then this extra argument is returned instead of null value.
HashMap.getOrDefault() method
getOrDefault(K key, V defaultValue)

Java HashMap Example 7 : Using getOrDefault() method of HashMap, get the Price of the Book named with "Programming In Java" and "Digital Electronics" from the HashMap

Integer priceOne = bookNameWithPrice.getOrDefault("Programming In Java", 500);
System.out.println("Price of the Book named with Programming In Java : " + priceOne);
Integer priceTwo = bookNameWithPrice.getOrDefault("Digital Electronics", 300);
System.out.println("Price of the Book named with Digital Electronics : " + priceTwo);
Output
Price of the Book named with Programming In Java : 450
Price of the Book named with Digital Electronics : 300
Note : As the Digital Electronics is not found in the HashMap so that the 300 is returned.

Collection Views Provided by HashMap in Java

As we know, HashMap is not a Collection because it doesn't implement the Collection interface. But HashMap provide few methods that return equivalent Collection of the HashMap which is known as Collection View. There are 3 types of Collection View provided by the HashMap :
  • Entry Set Collection View
  • Key Set Collection View
  • Values Collection View
Lets look at them one-by-one :

Entry Set Collection View

The entrySet() method of the HashMap is used to get the Entry Set Collection View. This method provides a Set of all key-value pair stored into the HashMap where each pair is an instance of Map.Entry<K, V> interface, this interface is a part of java.util package and each instance of this interface represents a key-value pair stored in the HashMap.
Set<Entry<String, Integer>> entrySet = hashMap.entrySet();

Java HashMap Example 8 : Iterate over the HashMap through the Entry Set Collection View.

HashMap<String, Integer> bookNameWithPrice = new HashMap<>();

bookNameWithPrice.put("Programming In Java", 450);
bookNameWithPrice.put("Introduction to Algorithms", 800);
bookNameWithPrice.put("Data Structures", 600);
bookNameWithPrice.put("Programming In C" , 350);

Set<Entry<String, Integer>> entrySet = bookNameWithPrice.entrySet();

entrySet.forEach(entry -> {
     System.out.println("[ " + entry.getKey() + " : " + entry.getValue() + " ]");
});
Output
[ Programming In Java : 450 ]
[ Programming In C : 350 ]
[ Introduction to Algorithms : 800 ]
[ Data Structures : 600 ]

Key Set Collection View

The keySet() method of the HashMap is used to get the Ket Set Collection View. This method provides a Set which contains all the key object stored into the HashMap.
Set<String> keySet = hashMap.keySet();

Java HashMap Example 9 : Print all the keys stored into the HashMap

HashMap<String, Integer> bookNameWithPrice = new HashMap<>();

bookNameWithPrice.put("Programming In Java", 450);
bookNameWithPrice.put("Introduction to Algorithms", 800);
bookNameWithPrice.put("Data Structures", 600);
bookNameWithPrice.put("Programming In C" , 350);

Set<String> keySet = bookNameWithPrice.keySet();

System.out.println(keySet);
Output
[Programming In Java, Programming In C, Introduction to Algorithms, Data Structures]

Values Collection View

The values() method of the HashMap is used to get the Values Collection View. This method returns a Collection of all the values object stored into the HashMap.
Collection<Integer> values = hashMap.values();

Java HashMap Example 10 : Print all the values object stored into the HashMap

HashMap<String, Integer> bookNameWithPrice = new HashMap<>();

bookNameWithPrice.put("Programming In Java", 450);
bookNameWithPrice.put("Introduction to Algorithms", 800);
bookNameWithPrice.put("Data Structures", 600);
bookNameWithPrice.put("Programming In C" , 350);

Collection<Integer> values = bookNameWithPrice.values();

System.out.println(values);
Output
[450, 350, 800, 600]
Note : As we can see, the key-value pair order of any Collection View is different from the insertion order because the HashMap doesn't maintain any order.

How to check whether a key or a value is present or not within the HashMap in Java?

HashMap provides methods from that we can know whether the HashMap contains any particular key or value?. There are two methods to do this, those are containsKey() and containsValue().

Check whether the HashMap contains the given Key or not?

To do this, we have a method named as containsKey(), the containsKey() method takes an argument and returns true if the HashMap contains that argument as the key Otherwise, it gives false.

Java HashMap Example 11 : Using containsKey() method of HashMap in Java, check whether the book named as "Programming In Java" is present or not

System.out.println("Keys of HashMap : " + bookNameWithPrice.keySet());
boolean isJavaBookExists = bookNameWithPrice.containsKey("Programming In Java");
if(isJavaBookExists){
       System.out.println("Programming In Java is present in the HashMap");
}
Output
Keys of HashMap : [Computer Networks, Programming In Java, Programming In C, Introduction to Algorithms, Data Structures]
Programming In Java is present in the HashMap

Check whether the HashMap contains the given Value or not?

To do this, we have a method named as containsValue(), the containsValue() method takes an argument and returns true if the HashMap contains that argument as the Value Otherwise, it gives false.

Java HashMap Example 12 : Using containsValue() method of HashMap in Java, check whether any book having price 250

System.out.println("Values of HashMap : " + bookNameWithPrice.values());
boolean anyBookWith250Price = bookNameWithPrice.containsValue(250);
if(anyBookWith250Price){
       System.out.println("Yes! there is a book whose price is 250");
} else { 
       System.out.println("Oops! No book found for the price 250");
}
Output
Values of HashMap : [350, 450, 350, 800, 600]
Oops! No book found for the price 250

Few more methods of HashMap in Java

size() : returns the number of key-value pairs are stored into the HashMap in Java.
isEmpty() : check whether the HashMap is empty or not. If this method returns true that shows HashMap is empty otherwise it is not.
remove() : to remove the key-value pair, this method takes a key as the argument and removes the key-value pair mapped with this key from the HashMap in Java.

Java HashMap Example 13 : Combined Example of all the method discussed above.

HashMap<String, Integer> bookNameWithPrice = new HashMap<>();

bookNameWithPrice.put("Programming In Java", 450);
bookNameWithPrice.put("Introduction to Algorithms", 800);
bookNameWithPrice.put("Data Structures", 600);
bookNameWithPrice.put("Programming In C" , 350);

System.out.println("---------------------size()----------------------");
int size = bookNameWithPrice.size();
System.out.println("Size of the HashMap : " + size);

System.out.println("---------------------remove()--------------------");
System.out.println("HashMap before removing the any key-value pair : ");
System.out.println(bookNameWithPrice);

bookNameWithPrice.remove("Programming In Java");

System.out.println("HashMap after removing the any key-value pair : ");
System.out.println(bookNameWithPrice);

System.out.println("---------------------isEmpty()------------------");
HashMap<String, Integer> hashMap = new HashMap<>();
if(hashMap.isEmpty()){
      System.out.println("This is an Empty HashMap");
}
Output
---------------------size()----------------------
Size of the HashMap : 4
---------------------remove()--------------------
HashMap before removing the any key-value pair : 
{Programming In Java=450, Programming In C=350, Introduction to Algorithms=800, Data Structures=600}
HashMap after removing the any key-value pair : 
{Programming In C=350, Introduction to Algorithms=800, Data Structures=600}
---------------------isEmpty()------------------
This is an Empty HashMap

Conclusion

In this article, we have discussed what is HashMap in Java, how to instantiate it and the Hierarchy of the HashMap. Also, we have learned how to use various methods and different Collection Views provided by the HashMap in Java.

Related Article

Comments

Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

ArrayList in Java

ArrayList in Java In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.
Table of ContentsWhat is ArrayList in Java?Hierarchy of the ArrayList in java?How to create objects of ArrayList in Java?How to create an ArrayList of Custom Objects?How to iterate ArrayList in Java?How to get the elements by index from ArrayList in Java?How to check whether an elements is stored in the ArrayList in Java?How to remove elements from the ArrayList in Java?Few more methods of ArrayList in Java?
What is ArrayList in Java? ArrayList in Java is a List in which we can store and retrieve elemen…