Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise

No lessons available

CONTENTS

26. HashMaps: Key-Value Architecture

Storing data in associative dictionaries for lightning fast lookups.

Feb 22, 20264 views0 likes0 fires
18px

[!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.");

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
7 questions5 min

Continue Learning

27. HashSets: The Art of Uniqueness

Intermediate
7 min

28. Iterator: Safe Collection Traversal

Advanced
9 min

29. Wrapper Classes & Autoboxing

Intermediate
8 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 Java Programming: From Zero to EnterpriseAll Categories