---
description: A HashMap designates unique keys to corresponding values that can be retrieved at any given point. In this tutorial, learn how to use HashMaps in Java with example.
title: HashMap in Java
image: https://www.guru99.com/images/hashmap-in-java.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

HashMap in Java stores data as unique key-value pairs that can be retrieved quickly using the key. It holds object references rather than primitives, so wrapper classes are used, and offers methods such as put, get, remove, and containsKey.

* 🗝️ **HashMap Defined:** Stores unique keys mapped to values for fast retrieval by key.
* 📦 **Object References:** Holds objects only, so use wrapper classes like Integer instead of primitives.
* 🔧 **Core Methods:** put() stores a pair, get() retrieves a value, remove() deletes by key.
* 🔍 **Lookups:** containsKey(), keySet(), values(), and isEmpty() inspect the map’s contents.
* 🧪 **Examples:** Sample programs build a map, print it, and remove an entry by key.

[ Read More ](javascript:void%280%29;) 

![HashMap in Java](https://www.guru99.com/images/hashmap-in-java.png)

## What is Hashmap in Java?

A HashMap basically designates **unique keys** to corresponding **values** that can be retrieved at any given point.

[![HashMap in Java](https://www.guru99.com/images/uploads/2012/12/java6.jpg)](https://www.guru99.com/images/uploads/2012/12/java6.jpg)

## Features of Java Hashmap

a) The **values** can be stored in a map by forming a **key-value** pair. The value can be retrieved using the key by passing it to the correct method.

b) If **no element** exists in the Map, it will throw a ‘**NoSuchElementException’**.

c) HashMap stores only **object references**. That is why, it is impossible to use **primitive data types** like double or int. Use wrapper class (like Integer or Double) instead.

[](https://www.guru99.com/images/uploads/2012/12/java11.jpg)

## Using HashMaps in Java Programs:

Following are the two ways to declare a Hash Map:

HashMap<String, Object> map = new HashMap<String, Object>();
HashMap x  = new HashMap();

**Important Hashmap Methods**

* **get(Object KEY)** – This will return the value associated with a specified key in this Java hashmap.
* **put(Object KEY, String VALUE)** – This method stores the specified value and associates it with the specified key in this map.

## Java Hashmap Example

**Following is a sample implementation of java Hash Map:**

import java.util.HashMap;
import java.util.Map;
public class Sample_TestMaps{
  public static void main(String[] args){
    Map<String, String> objMap = new HashMap<String, String>();
    objMap.put("Name", "Suzuki");
    objMap.put("Power", "220");
    objMap.put("Type", "2-wheeler");
    objMap.put("Price", "85000");
    System.out.println("Elements of the Map:");
    System.out.println(objMap);
  }
}

**Output:**

Elements of the Map:
{Type=2-wheeler, Price=85000, Power=220, Name=Suzuki}

## Example: Remove a value from HashMap based on key

import java.util.*;
public class HashMapExample {
   public static void main(String args[]) {
   // create and populate hash map
   HashMap<Integer, String> map = new HashMap<Integer, String>();
   map.put(1,"Java");
   map.put(2, "Python");
   map.put(3, "PHP");
   map.put(4, "SQL");
   map.put(5, "C++");
   System.out.println("Tutorial in Guru99: "+ map);
   // Remove value of key 5
   map.remove(5);
   System.out.println("Tutorial in Guru99 After Remove: "+ map);
   }
}

**Output:**

Tutorial in Guru99: {1=Java, 2=Python, 3=PHP, 4=SQL, 5=C++}
Tutorial in Guru99 After Remove: {1=Java, 2=Python, 3=PHP, 4=SQL}

### RELATED ARTICLES

* [Encapsulation in Java ](https://www.guru99.com/encapsulation-in-java.html "Encapsulation in Java")
* [Split() String Method in Java: How to Split String with Example ](https://www.guru99.com/how-to-split-a-string-in-java.html "Split() String Method in Java: How to Split String with Example")
* [How to Reverse a String in Java using Recursion ](https://www.guru99.com/java-program-reverse-string.html "How to Reverse a String in Java using Recursion")
* [Kotlin vs Java – Difference Between Them ](https://www.guru99.com/kotlin-vs-java-difference.html "Kotlin vs Java – Difference Between Them")

## Lets us ask a few queries to the Hash Map itself to know it better

**_Q: So Mr.Hash Map, how can I find if a particular key has been assigned to you?_**

A: Cool, you can use the containsKey(Object KEY) method with me, it will return a Boolean value if I have a value for the given key.

**_Q: How do I find all the available keys that are present on the Map?_**

A: I have a method called as **keyset**() that will return all the keys on the map. In the above example, if you write a line as –  
**System.out.println(objMap.keySet());**

It will return an **output** as-  
\[Name, Type, Power, Price\]

Similarly, if you need all the values only, I have a method of **values**().  
**System.out.println(objMap.values());**

It will return an **output** as-  
\[Suzuki, 2-wheeler, 220, 85000\]

**_Q: Suppose, I need to remove only a particular key from the Map, do I need to delete the entire Map?_**

A: No buddy!! I have a method of **remove**(Object KEY) that will remove only that particular key-value pair.

**_Q: How can we check if you actually contain some key-value pairs?_**

A: Just check if I am empty or not!! In short, use **isEmpty**() method against me..

## FAQs

⚖️ What is the difference between HashMap and Hashtable in Java?

HashMap is non-synchronized and allows one null key and multiple null values, making it faster for single-threaded use. Hashtable is synchronized and does not allow null keys or values, making it thread-safe but slower.

🈳 Can a HashMap have null keys or values?

Yes. A HashMap permits exactly one null key and any number of null values. Attempting to add a second null key simply overwrites the value associated with the existing null key.

🔢 Is HashMap ordered in Java?

No. HashMap does not guarantee any order of its keys. If you need insertion order use LinkedHashMap, and if you need sorted order by key use TreeMap instead.

🤖 How can AI help choose the right Java collection?

AI can analyze access patterns such as lookups, ordering, and concurrency needs, then recommend HashMap, TreeMap, LinkedHashMap, or ConcurrentHashMap, helping developers pick the most efficient collection for their use case.

🧠 Can AI detect HashMap thread-safety issues?

Yes. AI-assisted analysis can flag a shared HashMap accessed by multiple threads without synchronization and recommend ConcurrentHashMap or external locking to prevent race conditions and data corruption.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/hashmap-in-java.png","url":"https://www.guru99.com/images/hashmap-in-java.png","width":"700","height":"250","caption":"HashMap in Java","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/hashmap-in-java.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/java-tutorials","name":"Java Tutorials"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/hashmap-in-java.html","name":"HashMap in Java"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/hashmap-in-java.html#webpage","url":"https://www.guru99.com/hashmap-in-java.html","name":"HashMap in Java","dateModified":"2026-06-30T17:25:48+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/hashmap-in-java.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/hashmap-in-java.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/james","name":"James Hartman","description":"I am James Hartman, a seasoned professional in Oracle Certified Java Professional tutorials, specializing in crafting comprehensive guides to help you excel in your Java certification journey.","url":"https://www.guru99.com/author/james","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","url":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","caption":"James Hartman","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Java Tutorials","headline":"HashMap in Java","description":"A HashMap designates unique keys to corresponding values that can be retrieved at any given point. In this tutorial, learn how to use HashMaps in Java with example.","keywords":"java","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/james","name":"James Hartman"},"dateModified":"2026-06-30T17:25:48+05:30","image":{"@id":"https://www.guru99.com/images/hashmap-in-java.png"},"copyrightYear":"2026","name":"HashMap in Java","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the difference between HashMap and Hashtable in Java?","acceptedAnswer":{"@type":"Answer","text":"HashMap is non-synchronized and allows one null key and multiple null values, making it faster for single-threaded use. Hashtable is synchronized and does not allow null keys or values, making it thread-safe but slower."}},{"@type":"Question","name":"Can a HashMap have null keys or values?","acceptedAnswer":{"@type":"Answer","text":"Yes. A HashMap permits exactly one null key and any number of null values. Attempting to add a second null key simply overwrites the value associated with the existing null key."}},{"@type":"Question","name":"Is HashMap ordered in Java?","acceptedAnswer":{"@type":"Answer","text":"No. HashMap does not guarantee any order of its keys. If you need insertion order use LinkedHashMap, and if you need sorted order by key use TreeMap instead."}},{"@type":"Question","name":"How can AI help choose the right Java collection?","acceptedAnswer":{"@type":"Answer","text":"AI can analyze access patterns such as lookups, ordering, and concurrency needs, then recommend HashMap, TreeMap, LinkedHashMap, or ConcurrentHashMap, helping developers pick the most efficient collection for their use case."}},{"@type":"Question","name":"Can AI detect HashMap thread-safety issues?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI-assisted analysis can flag a shared HashMap accessed by multiple threads without synchronization and recommend ConcurrentHashMap or external locking to prevent race conditions and data corruption."}}]}],"@id":"https://www.guru99.com/hashmap-in-java.html#schema-1126948","isPartOf":{"@id":"https://www.guru99.com/hashmap-in-java.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/hashmap-in-java.html#webpage"}}]}
```
