To use HashMap in Java, import java.util.HashMap, declare it as Map<KeyType, ValueType> map = new HashMap<>();, then call put() to add entries and get() to retrieve them. HashMap stores key-value pairs using hashing for O(1) average lookup, making it the go-to collection for fast data retrieval in Java applications.
A HashMap in Java is a data structure that stores key-value pairs, where each key is unique and maps to exactly one value. Think of it like a phone book: the name is the key, the number is the value. You can look up any entry instantly without scanning the whole list. Knowing how to use HashMap in Java is a core skill for any Java developer, and it comes up constantly in interviews and production code alike.
- Key Takeaway 1: HashMap stores data as key-value pairs and allows O(1) average-time lookup using hashing.
- Key Takeaway 2: It permits one null key and multiple null values, which makes it flexible but requires careful handling.
- Key Takeaway 3: HashMap is not thread-safe by default; use
ConcurrentHashMapin multi-threaded applications. - Key Takeaway 4: The Map interface in Java defines the contract; HashMap is just one implementation of it.
- Key Takeaway 5: Mastering HashMap methods like put, get, containsKey and entrySet will prepare you for both coding rounds and backend development work.
What HashMap Is
HashMap is part of the java.util package and implements the Map interface in Java. It was introduced in Java 1.2 and remains one of the most used collection types in the Java Collections Framework. According to the Stack Overflow Developer Survey 2024, Java consistently ranks among the top five most-used programming languages globally, and HashMap is taught in virtually every Java curriculum, from BTech programmes at IITs to BCA and MCA courses at state universities across India.
According to the JetBrains State of Developer Ecosystem 2024, collections and data structures — with HashMap at the top — are the most frequently used Java standard library features among professional developers worldwide. That usage pattern holds equally true in India’s product and service engineering teams, where HashMap appears in everything from e-commerce cart logic to banking transaction ledgers.
The internal mechanism is hashing. When you call put(“Riya”, 9876543210L), Java runs the key through a hash function, computes a bucket index, and stores the entry there. If two keys produce the same bucket index — a collision — Java chains the entries using a linked list or, from Java 8 onward, a balanced tree when the chain grows long. Retrieval works the same way: give it the key, it hashes it, finds the bucket, and returns the value. That is why average-case lookup is O(1), regardless of how many entries are in the map.
One property that catches beginners off guard: HashMap does not guarantee insertion order. If you iterate over it, entries may come back in any sequence. If order matters, use LinkedHashMap instead. Understanding the subjects covered in a BSc Computer Science degree will show you exactly where data structures like this sit in a full curriculum.
Core Properties of HashMap in Java
| Property | Detail |
|---|---|
| Null keys allowed | Yes, exactly one null key |
| Null values allowed | Yes, multiple null values |
| Maintains insertion order | No |
| Thread-safe | No (use ConcurrentHashMap for concurrency) |
| Default initial capacity | 16 buckets |
| Default load factor | 0.75 |
| Average time complexity (get/put) | O(1) |
The load factor of 0.75 is a performance balance point documented in the official Oracle Java documentation. When the map exceeds 75% capacity, it resizes and rehashes all existing entries into a larger bucket array, which is an expensive operation. Pre-sizing your HashMap when you know the expected entry count avoids that cost entirely.
Declaration and Syntax
The HashMap declaration in Java follows a straightforward generic syntax. You specify the type of the key and the type of the value inside angle brackets. Here is the most common pattern:
HashMap<String, Integer> scores = new HashMap<>();
That single line creates an empty map where keys are Strings and values are Integers. The diamond operator <> on the right lets Java infer the types from the left side. You can also declare it using the Map interface type on the left, which is the preferred style in professional code:
Map<String, Integer> scores = new HashMap<>();
Using the interface type on the left makes it easy to swap the implementation later without changing the rest of your code. This is a habit that separates junior developers from mid-level ones, and it is worth building early. Setting up a good IDE with static analysis is the fastest way to catch declaration mistakes before they reach production — see our guide on software development tools to learn first for a practical starting list. If you are also getting started with compiled languages more broadly, reading about how to write, compile and run a C program gives you a useful mental model for how Java compilation works too.
HashMap Syntax in Java: Step-by-Step
- Import the class: import java.util.HashMap; at the top of your file (or import java.util.*; for the whole package).
- Declare the map: Map<KeyType, ValueType> mapName = new HashMap<>();
- Add entries: mapName.put(“Arjun”, 85);
- Retrieve a value: int mark = mapName.get(“Arjun”);
- Iterate: use entrySet() to loop over all key-value pairs.
A common mistake at this stage is using primitive types like int or boolean as generic parameters. Java generics require wrapper classes, so use Integer, Boolean, Long and so on. Mixing this up throws a compile-time error that confuses beginners but is easy to fix once you know why it happens. You can read more about similar pitfalls in our guide on Java exceptions and common runtime errors.
Key HashMap Methods in Java
Knowing the right HashMap methods in Java is what makes you productive. The table below covers the most important ones with their return types and a brief description. These are the methods that appear most often in coding rounds at Indian product companies like Flipkart, Swiggy, Zepto and Razorpay, as well as in global FAANG interviews.
| Method | Return Type | What It Does |
|---|---|---|
| put(K key, V value) | V | Inserts or updates a key-value pair; returns the previous value or null |
| get(Object key) | V | Returns the value for the given key, or null if absent |
| getOrDefault(Object key, V defaultValue) | V | Returns the value, or a specified default if the key is not found |
| containsKey(Object key) | boolean | Returns true if the map contains the specified key |
| containsValue(Object value) | boolean | Returns true if one or more keys map to this value |
| remove(Object key) | V | Removes the entry for the key; returns the removed value or null |
| size() | int | Returns the number of key-value mappings |
| isEmpty() | boolean | Returns true if the map contains no entries |
| entrySet() | Set<Map.Entry<K,V>> | Returns a set view of all key-value pairs for iteration |
| keySet() | Set<K> | Returns a set of all keys |
| values() | Collection<V> | Returns a collection of all values |
| clear() | void | Removes all entries from the map |
How to Get Values from a Map in Java
To get values from a map in Java, you have two main options. Use get(key) when you are confident the key exists, and use getOrDefault(key, fallback) when it might not. For example, if you are building a student grade tracker for a class of 60 students at a Delhi or Pune engineering college:
Map<String, Integer> grades = new HashMap<>();
grades.put(“Priya”, 92);
int priyaScore = grades.getOrDefault(“Priya”, 0);
int absentScore = grades.getOrDefault(“Rahul”, 0); // returns 0, not null
Calling get() on a missing key returns null, and if you immediately unbox that into a primitive int, you get a NullPointerException. getOrDefault eliminates that risk cleanly. This is one of the most common bugs in real codebases, and using the safer method from day one is the right habit.
How to Iterate HashMap in Java
When you need both the key and the value during iteration, entrySet() is your tool. It returns a set of Map.Entry objects, each holding one key-value pair. A typical loop looks like this:
for (Map.Entry<String, Integer> entry : grades.entrySet()) {
System.out.println(entry.getKey() + ” scored ” + entry.getValue());
}
If you only need keys, use keySet(). If you only need values, use values(). Picking the right iterator avoids unnecessary object creation and keeps your code readable. These micro-decisions matter more as your codebase grows, which is something you appreciate quickly if you are working toward a full stack or software developer role.
HashMap with Custom Objects as Keys
A practical tip from real project work: always override equals() and hashCode() in any custom class you plan to use as a HashMap key. If you skip this, two objects with identical fields will be treated as different keys because Java compares object references by default. This is a silent bug that produces wrong results with no exception thrown, making it particularly hard to debug. The hashCode method determines which bucket the entry lands in; equals then confirms the exact match within that bucket. Both must be consistent for how to use HashMap in Java with custom keys to work correctly.
Map Interface vs HashMap in Java
The Map interface in Java is a contract defined in java.util. It specifies what a map must do: store key-value pairs, retrieve by key, check for key existence, and so on. HashMap is one concrete class that fulfils that contract. TreeMap and LinkedHashMap are two others.
The difference matters in practice. If you declare your variable as Map<String, Integer> map, you can swap the implementation from HashMap to TreeMap (which sorts by key) without touching any other line of code. If you declare it as HashMap<String, Integer> map, you lock yourself in. Most experienced Java developers declare with the interface and instantiate with the implementation, every time.
Quick Comparison: Map Implementations in Java
| Feature | HashMap | LinkedHashMap | TreeMap |
|---|---|---|---|
| Order | No order | Insertion order | Sorted by key |
| Null keys | One allowed | One allowed | Not allowed |
| Performance (get/put) | O(1) average | O(1) average | O(log n) |
| Thread-safe | No | No | No |
| Best use case | General-purpose fast lookup | Cache with access order | Sorted data traversal |
According to the TIOBE Index for early 2025, Java holds a top-three position among the most popular programming languages worldwide. HashMap is covered in virtually every Java course, from undergraduate data structures modules at IITs and NITs to backend engineering bootcamps. In India, where over 5 million software developers are active according to NASSCOM estimates, HashMap fluency is tested in nearly every Java-related placement drive. If you are preparing for placements at product companies or planning to work in backend development, getting HashMap fluent is non-negotiable. Explore what careers look like after a postgraduate degree in our guide on jobs and salary after MCA.
Here is where you stand and what to do next. You now know how to use HashMap in Java, from declaration to iteration to the difference between the Map interface and its implementations. That knowledge transfers directly into backend APIs, caching logic, frequency counting problems, and dozens of common coding interview questions.
- This week: Write a small Java program that reads a list of student names and marks, stores them in a HashMap, and prints the top scorer using entrySet() iteration.
- Next: Study how equals() and hashCode() affect HashMap behaviour when using custom objects as keys. The Oracle Java docs are the best reference for this.
- Then: Explore 3.0 University’s online certification courses in Cybersecurity, AI, Ethical Hacking and Blockchain. Strong Java and data structure fundamentals are the foundation for secure coding, exploit development and AI-driven security work. If you want a structured path into cybersecurity, the CEH v13 AI online course at 3.0 University is a practical next step that builds directly on the programming skills you are developing now.
Frequently Asked Questions
What is a HashMap in Java?
A HashMap in Java is a collection class in the java.util package that stores data as key-value pairs. Each key is unique, and it maps to exactly one value. Internally it uses hashing to achieve average O(1) time complexity for both insertion and retrieval, making it one of the fastest data structures for lookup-heavy operations.
How do I declare a HashMap in Java?
Use the syntax Map<KeyType, ValueType> map = new HashMap<>(); after importing java.util.HashMap. Declaring with the Map interface on the left is preferred in professional code because it keeps your implementation swappable. Key and value types must be wrapper classes like String, Integer or Long, not primitives.
What are the main HashMap methods in Java?
The most commonly used HashMap methods are put() to insert or update a pair, get() to retrieve a value by key, getOrDefault() for safe retrieval with a fallback, containsKey() to check existence, remove() to delete an entry, entrySet() for full iteration, and size() to count entries. These cover the vast majority of real-world use cases.
What is the difference between Map and HashMap in Java?
Map is an interface that defines the contract for key-value storage. HashMap is a concrete class that implements that interface using a hash table. You can also implement Map with TreeMap or LinkedHashMap. Declaring your variable as Map rather than HashMap makes your code more flexible and is considered best practice in Java development.
How do I get values from a Map in Java?
Use map.get(key) to retrieve a value directly; it returns null if the key is absent. Use map.getOrDefault(key, defaultValue) to avoid null and provide a safe fallback. To iterate over all values, call map.values() or loop through map.entrySet() to access both keys and values together in a single pass.
What is the difference between HashMap and Hashtable in Java?
HashMap is not synchronized and permits one null key and multiple null values. Hashtable is synchronized, making it thread-safe, but it does not allow any null keys or values. In modern Java, ConcurrentHashMap is preferred over Hashtable for thread-safe operations because it offers better performance through segment-level locking rather than locking the entire map.
How does HashMap handle collisions in Java?
When two keys hash to the same bucket index, HashMap stores both entries in that bucket using a linked list. From Java 8 onward, if a single bucket accumulates more than eight entries, the linked list is converted to a balanced red-black tree, improving worst-case lookup from O(n) to O(log n). Good hashCode implementations minimize collisions and keep performance close to O(1).
Last updated: June 2025. Reviewed by the 3University editorial team.