Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Wednesday, November 10, 2021

How to HashMap in Java? Example Tutorial

Hello friends, we are here today again on our journey to Java. I hope everyone is fine and ready to board our train of knowledge. Today we are gonna learn something very interesting and very exciting, yes I am talking about the HashMap class in Java which is the implementation of hash table data structure. In the past, I have shared my thoughts on How HashMap works in Java as well as frequently asked HashMap interview questions but I have never shared an example of how to use HashMap in Java, or when to use HashMap. Today's topic will definitely be very useful in coding and programming. This topic would surely decrease your time complexity if any task very significantly :p 

So what's the wait? Let's start!

As always, we will start understanding today's topic by a scenario. let's say we have a classroom. And, for the classroom, we need to conduct exams. For this exam, we need to match each student's name with student roll numbers. How will you keep a record for this scenario?

Think for 2 minutes over the scenario and then we will discuss the solutions. Again, there are multiple solutions for the problem, but we will focus on the topic we are discussing.

Now, if you guys are thinking of taking 2 arrays, one for names and one for roll numbers, think if what if we need to add a few more students? thus, let's say we keep an ArrayList. Now array lists are sequential in nature. 

So, we can use 2 ArrayLists to store the data. But, now suppose we need to find the name/roll number of a particular student. we would need to travel the roll number list and find the index and get the corresponding name from the 2nd array list. 

This is fine, but for each such query, we would get O(n) time complexity considering that the size of each ArrayList is n. Can we drop down the time complexity?

Think for 2 minutes and then we will discuss the solution. Hope you all have brainstormed enough. Now, let's discuss the solution. Before that, let's discuss today's topic, and then you guys can know/tell if we can use this for our solution. 

1. HashMap class in Java

The HashMap class in Java 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 overwrite the matching key's element. 

Updating, deleting, and other actions are simple to execute using the key index. The java.util package contains the HashMap class.

In Java, HashMap is similar to Hashtable, however, it is not synchronized. It also allows us to store null items, however, only one null key should be used. 

Since Java 5, it's been referred to as HashMap<K,V>, with K denoting key and V denoting value. It implements the Map interface and inherits the AbstractMap class.  You can also see these best Java Collections and Stream courses to learn more about the HashMap class in Java. 

2. HashMap Declaration:

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

It takes two parameters namely as follows:

  • The type of keys maintained by this map
  • The type of mapped values

Now, let's see a working code of HashMap and take the example of our scenario discussed above. 

3. How to use HashMap in Java - Code Example

Here is our complete code example to demonstrate how to use the HashMap class in Java. As I said it's an implementation of hash table data structure and you can use HashMap whenever you need a hash table in Java. 

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

public class MyMap {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Student1", 1);
map.put("Tom Cruise", 3);
map.put("Bond, James Bond", 7);
map.put("Selmon Bhoi", 0);
map.put(null, 9);

System.out.println("traversing map");
map.forEach((key, value) -> System.out.println(key + " --> " + value));

System.out.println("getting values from map now...");

System.out.println(map.get("Selmon Bhoi"));
System.out.println(map.get("Tom Cruise"));



You can see the output below:

Now, you guys must know why HashMap is very useful. It stored the key and values in pairs and with a condition that the key must be unique, else, it is overridden. Now, the main benefit of HashMap is that getting any value from the key is in O(1) time complexity! Yes, you heard right!

You guys must be curious on why HashMap gives O(1) time complexity and how?! 
HashMap internally calculates the 'hash' of the key and stores value corresponding to a key on the basis of that 'hash'. 

So, as each key is unique, we get a unique hash for each of them (Not necessarily, this is also overcome and we will discuss this in the next article). So, getting a value from the key is performed in O(1) time complexity. Pretty cool right :p

4. Important Points about HashMap in Java

Now, let's revise the important points about HashMap in Java which I believe every Java developer should know and remember
  • The value of a Java HashMap is determined by the key.
  • Only unique keys are stored in the Java HashMap.
  • One null key and several null values are possible in a Java HashMap.
  • HashMap in Java is not synchronized.
  • HashMap in Java does not keep track of the order.
  • The capacity of the Java HashMap class is 16 by default, with a load factor of 0.75.

Hope you guys enjoyed the article. Don't forget to try hands-on HashMap in Java.

Till next article, peace :D

Related Java HashMap tutorials  you may like
  • How does get() method of HashMap work in Java? (answer)
  • HashMap vs Hashtable in Java? (answer)
  • ArrayList vs HashMap in Java? (answer)
  • HashSet vs HashMap in Java? (answer)
  • Difference between ConcurrentHashMap and HashMap in Java? (answer)
  • How HashSet internally works in Java? (answer)
  • How ConcurrentHashMap internally works in Java? (answer)
  • HashMap vs LinkedHashMap in Java? (answer)
  • The best way to iterate over HashMap in Java? (answer)
  • How to sort the HashMap on keys and values in Java? (solution)
  • 3 ways to loop over a Map in Java? (example)
  • HashMap vs ConcurrentHashMap in Java? (answer)
  • Difference between ArrayList and HashMap? (difference)
  • How to convert Map to List in Java? (solution)

Thanks for reading this article so far. If you like this Java HashMap Tutorial and example then please share with your friends and colleages. If you have any questions or feedback, please ask in comments. 

P. S. - If you are new to Java and want to learn core Java in depth, you can also checkout these 10 Free Core Java Courses to staart with. It contains best free Java courses from Udemy and Coursera for beginners. 

No comments :

Post a Comment