Skip to main content

Command Palette

Search for a command to run...

#1 Features of Java HashMap

Updated
2 min read
#1 Features of Java HashMap
A
Machine Learning Engineer and open-source developer focused on NLP, LLM applications, Retrieval-Augmented Generation (RAG), semantic search, and AI infrastructure. I enjoy building developer tools, portable AI systems, and production-ready ML pipelines using Python, FastAPI, FAISS, LangChain, TensorFlow, and PyTorch. Creator of: • RagBucket — portable executable RAG artifacts for Python • LazyTune — fast hyperparameter optimization library • AkBOT — AI portfolio chatbot using RAG Contributor to open-source projects including NumPy and LocalStack.

HashMap is one of the most commonly used classes in Java Collections Framework. It stores data in key-value pairs and provides fast data access.

Example:

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

map.put(1, "Java");
map.put(2, "Python");

System.out.println(map.get(1));

Output:

Java

1. Stores Data in Key-Value Pairs

Each element in a HashMap consists of:

  • Key

  • Value

Example:

map.put(101, "Anik");
  • 101 → Key

  • "Anik" → Value


2. Unique Keys

HashMap does not allow duplicate keys.

map.put(1, "Java");
map.put(1, "Python");

The old value gets replaced.

Output:

{1=Python}

3. Allows Duplicate Values

Different keys can have the same value.

map.put(1, "Java");
map.put(2, "Java");

Valid in HashMap.


4. Fast Performance

Operations like:

  • put()

  • get()

  • remove()

work in approximately O(1) time complexity.

This makes HashMap very efficient.


5. Allows One Null Key

HashMap allows:

  • One null key

  • Multiple null values

Example:

map.put(null, "Java");
map.put(2, null);

6. Unordered Collection

HashMap does not maintain insertion order.

Example:

map.put(3, "C");
map.put(1, "Java");
map.put(2, "Python");

Output order may vary.


7. Not Synchronized

HashMap is not thread-safe.

It is faster than synchronized collections because multiple threads can access it simultaneously.

For thread safety, Java provides:

ConcurrentHashMap

8. Part of Java Collections Framework

HashMap belongs to:

java.util

Package.

Import statement:

import java.util.HashMap;

9. Uses Hashing Internally

HashMap uses a hashing mechanism to store and retrieve elements efficiently.

Internally it uses:

  • Hash function

  • Buckets

  • Hash codes


10. Dynamic in Size

HashMap automatically grows when more elements are added.

No need to define fixed size manually.


A phone contacts app:

Name Phone Number
Anik 9876543210
Rahul 9123456780
  • Name → Key

  • Phone Number → Value