Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
3. Core APIs & I/O
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

26. HashMaps: Key-Value Architecture

Storing data in associative dictionaries for lightning fast lookups.

Java Programming: From Zero to Enterprise
3. Core APIs & I/O
February 22, 2026
66
A

[!NOTE] Lists are great for storing sequential chains of items. But what if you need to rapidly search the collection? Searching a list of 1,000,000 users for a specific username takes a long time.

This is where dictionaries—or HashMaps in Java—become essential.

What is a HashMap?

A HashMap stores items in "key/value" pairs. You look up the "key", and it instantly spits out the "value" regardless of how large the dataset is.

If you want to store the capital cities of various countries:

  • Key: The Country Name (String)
  • Value: The Capital City Name (String)

Because it uses a highly complex mathematical hashing algorithm internally, a HashMap can retrieve an item out of 10,000,000 records in O(1) time (practically instantaneous), whereas an ArrayList might take O(N) time (checking each item in sequentially).

Syntax and Basics

To use it, import it from java.util.HashMap. Notice that when we establish the generics, we must provide TWO types: one for the Key, one for the Value.

import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    // We create a HashMap that accepts a 'String' key, and maps it to a 'String' value
    HashMap<String, String> capitalCities = new HashMap<String, String>();

    // 1. ADDING DATA: We use .put() instead of .add()
    capitalCities.put("England", "London");
    capitalCities.put("Germany", "Berlin");
    capitalCities.put("Norway", "Oslo");
    capitalCities.put("USA", "Washington DC");

    // 2. RETRIEVING DATA: We pass the exact key
    System.out.println(capitalCities.get("England")); // Outputs "London"
    
    // 3. REMOVING DATA: Pass the exact key
    capitalCities.remove("England");
    
    // 4. CHECKING EXISTENCE: Lightning fast lookups!
    if (capitalCities.containsKey("USA")) {
        System.out.println("We have data for the USA!");
    }
  }
}

Modifying Existing Keys

A HashMap specifically uses a mathematical hash of the Key to locate the value in memory. Therefore, Keys must be absolutely unique!

If you use .put() with a key that already exists, it does not create a duplicate entry. Instead, it completely overwrites and destroys the old value with the new one.

capitalCities.put("USA", "Washington DC");
capitalCities.put("USA", "New York"); // OVERWRITES THE PREVIOUS LINE!

Advanced Types

You can mix and match types securely. Want to store the names of people mapping to their age?

// Key: String. Value: Integer wrapper.
HashMap<String, Integer> peopleAges = new HashMap<String, Integer>();
peopleAges.put("John", 32);
peopleAges.put("Steve", 45);

System.out.println("Steve is " + peopleAges.get("Steve") + " years old.");

HashMap Patterns You Will Use Often

HashMap is one of the most useful Java collections because it turns a lookup problem into a key lookup. It is perfect for counting, caching, grouping, and quick existence checks with associated data.

Frequency Counting

String text = "banana";
Map<Character, Integer> frequency = new HashMap<>();

for (char ch : text.toCharArray()) {
    frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
}

Grouping Values

Map<String, List<String>> studentsByCity = new HashMap<>();

studentsByCity
    .computeIfAbsent("Delhi", city -> new ArrayList<>())
    .add("Asha");

getOrDefault and computeIfAbsent remove a lot of repetitive null-checking code.

Common Mistakes

  • Calling get() and assuming the result is never null.
  • Using mutable objects as keys and changing them after insertion.
  • Forgetting that keys are unique and values can repeat.
  • Expecting iteration order from plain HashMap.

Mini Practice

Count how many times each word appears in a sentence. Store the result in a HashMap<String, Integer> and print each word with its count.

Practice Lab: Word Frequency Counter

Use HashMap to count repeated values efficiently.

  1. Create a sentence such as "java is fun and java is powerful".
  2. Split it into words.
  3. Use HashMap<String, Integer> to count each word.
  4. Use getOrDefault to simplify counting.
  5. Print every word with its count.

Goal: Practice key-value thinking and frequency-map patterns.

Revision Checkpoint

  • HashMap: Stores key-value pairs.
  • Key uniqueness: One key maps to one current value.
  • put: Adds or replaces a value for a key.
  • containsKey: Fast membership check for keys.
  • Pattern: Excellent for counting and lookup problems.

Before the quiz: Write the mental shape of a frequency map for words.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava
Quiz: HashMaps
10 questions5 min
Lesson 6 of 10 in 3. Core APIs & I/O
Previous in 3. Core APIs & I/O
25. LinkedLists: The Alternative
Next in 3. Core APIs & I/O
27. HashSets: The Art of Uniqueness
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories