Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

HashMap in Java With Examples
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings
The fast well prepared banner

HashMap in Java With Examples

If you’re aiming to crack the world’s most challenging coding interviews, HashMap is an essential concept to have in your toolkit. In this article, we’ll discuss HashMaps, as used in Java, along with some examples.

In this article, we’ll cover:

  • What Is Java HashMap?
  • Features of Java Hashmap
  • HashMap Class Declaration
  • Example: Create HashMap in Java
  • HashMap Class Methods
  • Constructors in HashMap
  • The Time Complexity of HashMap
  • Applications of HashMap
  • Creating HashMap From Another Class That Implements Map Interface
  • Difference Between HashMap and HashSet in Java
  • Java HashMaps Interview Questions
  • Java HashMaps FAQs

What Is Java HashMap?

HashMap<K, V> is a class we can find in the Java.util package. The HashMap class is the implementation of the Map interface of Java and consists of key-value pairs. We denote it by <Key, Value> pair; we can access it using the key, i.e., one must know the key to access the value stored at that key in HashMap.

A HashMap allocates unique keys to corresponding values, which we can access at any point. It stores elements in key-value pairs. Keys are unique identifiers used to link each value on a map. It will replace the value of the corresponding key on trying to insert a duplicate key.

The HashMap uses a "Hashing" technique. Hashing involves the conversion of a longer string into a shorter string by applying some algorithm to it. The string is converted to a shorter string as it makes the searching process faster.

Features of Java Hashmap

  • The storage of the values in a map is in the form of a key-value pair. We can access it by passing the key to the correct method.
  • If no value exists for the passed key, it will throw “NoSuchElementException.”
  • HashMap only stores object reference, making it impossible to use primitive data types like double or int. Instead, we can use wrapper classes (like Integer or Double).

HashMap Class Declaration

public class HashMap<Key,Value> extends AbstractMap<Key,Value>implements Map<Key,Value>, Cloneable, Serializable

 Class Parameters:

  • Key: Type of key object.
  • Value: Type of value object.

 We can declare the Map in the following ways:

HashMap<Key,Value> myMap1 = new HashMap<Key,Value>();

HashMap myMap2 = new HashMap();

Here is the example containing the declaration of HashMap in java. 

Example: Creating HashMap in Java

Code: 

import java.util.HashMap;


class Main {

  public static void main(String[] args) {


    // Creating HashMap.

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

 

/*  

  It can be also declared like: HashMap<String, Integer> myMap= new HashMap<String, Integer>();

*/

    // Adding Elements to the HashMap

    myMap.put("IK", 1);

    myMap.put("HM", 2);

    myMap.put("TM", 3);

    

    // Printing HashMap

    System.out.println("myMap: " + myMap);

  }

}

Output:

myMap: {IK=1, HM=2, TM=3}

HashMap Class Methods

List of some methods available for class HashMap in Java.

  • void clear(): We can use this method to erase all the key and value pairs from the specified Map. 
  • Object clone(): It returns a new copy of all the mappings, and we can use this for cloning it into another Map.
  • boolean containsKey(Object key): The basis of this boolean function value is whether a particular key exists in Map or not.
  • boolean containsValue(Object Value): The basis of this boolean function value is whether a particular value exists in Map or not.
  • Value get(Object key): We can use it to get the value associated with a particular key.
  • boolean isEmpty(): It returns a boolean value based on whether the Map is empty or not.
  • Set keySet(): This function returns a set containing all keys in the Map.
  • Value put(Key k, Value v): We can use this function to insert the key-value pair in the Map. 
  • int size(): We can use this function to return the size of Map; size is the number of key-value pairs in the Map.
  • Collection values(): We can use this function to return the collection of values present in the Map.
  • Value remove(Object key): We can use this function to remove a particular key-value pair associated with the passed key, and it will return the value of the removed pair.  
  • void putAll(Map m): We can use this method to copy all Map elements to another Map.
  • entrySet(): This method returns the set view of key/value pairs in a map.

Here is an example containing the implementation of some basic methods of HashMap.

Example: Methods in Java

Code:

import java.util.HashMap;


public class Main {

  public static void main(String[] args) {


    // Creating HashMap.

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


    // put() method to add elements in the HashMap.

    myMap.put("IK", 1);

    myMap.put("HM", 2);

    myMap.put("TM", 3);


    // Printing HashMap

    System.out.println("HashMap: " + myMap);



    // get() method to get value associated with a particular key.

    String key = "IK";

    int val= myMap.get(key);

    System.out.println("Value related to key IK: " + val);


    // Using keySet() to return a set view of keys.

    System.out.println("Keys: " + myMap.keySet());


    // Using values() to return a set view of values.

    System.out.println("Values: " + myMap.values());


    // Using entrySet() to return a set view of key/value pairs.

    System.out.println("Key/Value mappings: " + myMap.entrySet());

    

    System.out.println("Original HashMap: " + myMap);


    // Changing element with key IK.

    myMap.replace("IK", 5);

    System.out.println("HashMap after using replace(): " + myMap);

    

    // Remove elements associated with the key IK.

    val = myMap.remove("IK");

    System.out.println("Removed value: " + val);


    System.out.println("Updated HashMap: " + myMap);

    

  }

}


Output:


HashMap: {IK=1, HM=2, TM=3}

Value related to key IK: 1

Keys: [IK, HM, TM]

Values: [1, 2, 3]

Key/Value mappings: [IK=1, HM=2, TM=3]

Original HashMap: {IK=1, HM=2, TM=3}

HashMap using replace(): {IK=5, HM=2, TM=3}

Removed value: 5

Updated HashMap: {HM=2, TM=3}

Constructors in HashMap

We need to see some key terms before studying this topic:

Initial Capacity: Capacity of the Map at the time of its creation. 

Load Factor: Percentage value of the Map’s capacity, after which we need the capacity of Hashmap to increase.  

HashMap provides four constructors, and the access modifier of each is public:

  1. HashMap(): The default constructor creates an instance of HashMap with an initial capacity of 16 and Load Factor 0.75.

    Syntax: HashMap<K, V> hm = new HashMap<K, V>();

  2. HashMap(int initialCapacity): This constructor creates a HashMap instance with some specified initial capacity and a load factor of 0.75.

    Syntax: HashMap<K, V> hm = new HashMap<K, V>(int initialCapacity);

  3. HashMap(int initialCapacity, float loadFactor): This constructor creates a HashMap instance with a specified initial capacity and load factor.

    Syntax: HashMap<K, V> hm = new HashMap<K, V>(int initialCapacity, int loadFactor);

  4. HashMap(Map map): This constructor creates an instance of HashMap with the same mappings as that of the specified Map.

    Syntax: HashMap<K, V> hm = new HashMap<K, V>(Map map);

Iterate Through a HashMap

There are many ways to Iterate through HashMap. You can study them here in detail. 

Time complexity of HashMap 

The time complexity is constant for basic operations like get and put — O(1). 

Iterating over HashMap takes linear time complexity, i.e., O(n). As we are visiting each key-value pair and Iterating till the last element of the map, it is directly proportional to the sum: capacity + size of the Map. 

Applications of HashMap  

HashMap, at its core, is the implementation of Hashing. So, it can be useful where we need efficient implementation of operations like search, insert and delete.

It is used in the effective implementation of some useful algorithms like Dijkstra's Algorithm and Topological Sort.  

Creating HashMap From Another Class That implements Map interface

In Java, we can create a HashMap from other Maps.

Let’s imagine we already have created an object of Class TreeMap named myTreeMap.

Now, we will create an object of HashMap named myHashMap using the TreeMap.

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

The newly created myHashMap will contain all the key-value pairs of myTreeMap.

Example: Creating HashMap from TreeMap in Java

Code:

import java.util.HashMap;

import java.util.TreeMap;


class Main {

  public static void main(String[] args) {


    // Creating a Tree Map

    TreeMap<String, String> myTreeMap= new TreeMap<>();


    // Inserting Elements. 

    myTreeMap.put("IK", "InterviewKickstart");

    myTreeMap.put("TM", "TreeMap");

    

     // Printing the TreeMap

    System.out.println("TreeMap: " + myTreeMap);


    // Creating HashMap from the TreeMap

    HashMap<String, String> myHashMap= new HashMap(myTreeMap);

   

     // Inserting new key-value pair in HashMap. 

     myHashMap.put("HM", "HashMap");

     

     // Printing the HashMap

    System.out.println("HashMap: " + myHashMap);


  }

}

Output:

TreeMap: {IK = InterviewKickstart, TM = TreeMap}

HashMap: {IK = InterviewKickstart, TM = TreeMap, HM = HashMap}

Difference Between HashMap and HashSet in Java

Example

{1 -> a, 2 -> b, 3 -> c, 4 -> d}

{'a', 'b', 'c'}

Java HashMaps Interview Questions 

  1. How does the put() method of HashMap works in Java?
  2. How does HashMap handle collisions in Java?
  3. Which data structure HashMap represents? 
  4. What happens if we use HashMap in a Java multithreaded application?
  5. What are some ways to iterate over the HashMap in Java?
  6. How to remove the mapping while iterating over HashMap in Java?
  7. In which order are mappings stored in HashMap?

For more commonly asked interview questions at FAANG and tier-1 tech companies, visit the Interview Questions page. 

Java HashMaps FAQs

Question: What is the requirement for using Object as a key or value in HashMap? 

In HashMap, the key or value object must implement the equals() and hashcode() method. 

Because, When we insert the key object into the map, we need to use hashcode() there, while we need the equals() method when we try to get the value from the map.

The hashcode() method returns the integer value generated by the hashing algorithm, while the equals() method compares two strings based on the content of the strings.

Question: Can we store the null key in Java HashMap? 

Yes, we can store the null key because Java HashMap allows one null key. That will be stored at the first location of the bucket array here because hashCode() will throw NullPointerException on calling it on the null key. So, HashMap doesn't call the hashCode() method for the null key. Hence, when the user null calls the get() method, the value at the first index is returned.

Question: Can we store a duplicate key in HashMap?

No, we can not store the duplicate key in the HashMap. Java HashMap doesn't allow duplicate keys. If we try to insert an existing key with some value, it will replace the old value. But here, the size of HashMap will not change. 

Are You Ready to Nail Your Next Coding Interview?

Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of Software Engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

————

Article contributed by Omkar Deshkmukh

Last updated on: 
March 11, 2024
Author

Abhinav Rawat

Product Manager @ Interview Kickstart | Ex-upGrad | BITS Pilani. Working with hiring managers from top companies like Meta, Apple, Google, Amazon etc to build structured interview process BootCamps across domains

Attend our Free Webinar on How to Nail Your Next Technical Interview

Square

HashMap in Java With Examples

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image