Java HashMap and HashSet — Key-Value Lookup Explained
Learning Objectives
- Store and retrieve key value pairs with HashMap
- Enforce uniqueness with HashSet
- Explain hashing, buckets, and equals contracts
- Choose between Map and Set for a given problem
Overview
Lists preserve order and allow duplicates. Sometimes you need the opposite goals: unique items only, or lightning fast lookup by a meaningful key. HashMap and HashSet solve those problems with hashing, a technique that converts an object into a bucket number so the runtime can jump near the right slot instead of scanning everything.
HashMap implements Map and stores entries with a key and a value. HashSet implements Set and stores unique elements only; internally it delegates to a HashMap and uses the element as the key.
HashMap Basics
Create a map, put entries with put, read them with get, and check presence with containsKey. Keys must be unique: storing the same key twice replaces the previous value.
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Ann", 30);
ages.put("Bo", 25);
ages.put("Ann", 31);
System.out.println(ages.get("Ann"));
System.out.println(ages.getOrDefault("Zed", 0));
System.out.println(ages.containsKey("Bo"));
System.out.println(ages.size());
for (String key : ages.keySet()) {
System.out.println(key + " -> " + ages.get(key));
}
}
}
Notice that re-putting Ann updated the value rather than creating a second Ann entry. That behavior makes HashMap ideal for indexes, caches, and frequency counts.
Common Map Methods
| Method | Purpose |
|---|---|
| put key and value | Insert or replace an entry |
| get key | Fetch value or null if absent |
| getOrDefault | Fetch with a fallback |
| containsKey | Membership test for keys |
| remove key | Delete an entry |
| keySet | View of all keys |
| values | View of all values |
| entrySet | View of key and value pairs for loops |
Iterating entrySet is often the cleanest way to print a full map because each entry exposes both halves in one object.
HashSet Basics
A set stores each element once. Adding a duplicate returns false and changes nothing. Like HashMap, it relies on hashing for fast membership checks.
import java.util.HashSet;
import java.util.Set;
public class SetDemo {
public static void main(String[] args) {
Set<String> tags = new HashSet<>();
tags.add("java");
tags.add("coding");
tags.add("java");
System.out.println(tags.size());
System.out.println(tags.contains("coding"));
System.out.println(tags.remove("java"));
System.out.println(tags);
}
}
Because sets ignore order, the printed iteration order may not match insertion order. If you need sorted output, TreeSet is another choice; if you need insertion order, LinkedHashSet provides it.
How Hashing Works
When you put a key, Java calls the key hashCode method to get an integer, maps that integer to a bucket index, and stores the entry in that bucket. When values share a bucket, the structure keeps a small list or tree of entries and distinguishes them with equals.
That leads to a contract you must respect for custom keys: if two objects are equal according to equals, they must return the same hash code. Unequal objects may share a hash code, but good spread reduces collisions and keeps performance high.
class User {
String id;
String name;
User(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof User)) {
return false;
}
User that = (User) other;
return id.equals(that.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}
Overriding equals without hashCode breaks HashMap and HashSet behavior because equal keys may land in different buckets. IDEs can generate both methods for you.
Choosing HashMap or HashSet
Use HashMap when each identifier maps to a payload: user ids to profiles, product codes to prices, words to counts. Use HashSet when you only care whether an item exists: unique tags, processed node ids during a traversal, or deduplicated imports.
Both offer average constant time for the core operations under a good hash distribution. Worst case behavior degrades if every key collides, which is why a sensible hashCode matters in production systems.
Key Takeaways
💡
- HashMap stores unique keys with associated values; put replaces duplicates
- HashSet stores unique elements and is backed by hashing internally
- Average lookup cost is constant time when hashing spreads well
- Always override equals and hashCode together for custom key classes
- Use Map for associations and Set for membership
Practice Questions
- Write a program that counts how many times each word appears in an array using HashMap.
- Why must a custom key class override both equals and hashCode?
- Convert a HashSet of strings into an ArrayList so results print in list order.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions