🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Java HashMap and HashSet — Key-Value Lookup Explained

Java OOP and Core APIsMap and Set🟢 Free Lesson

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

MethodPurpose
put key and valueInsert or replace an entry
get keyFetch value or null if absent
getOrDefaultFetch with a fallback
containsKeyMembership test for keys
remove keyDelete an entry
keySetView of all keys
valuesView of all values
entrySetView 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

  1. Write a program that counts how many times each word appears in an array using HashMap.
  2. Why must a custom key class override both equals and hashCode?
  3. 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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Java Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement