CodeGym /Courses /JAVA 25 SELF /“Your own dictionary” — Ha...

“Your own dictionary” — HashMap<K,V>

JAVA 25 SELF
Level 12, Lesson 2
Available

1. Introduction

We already know that ArrayList is an “infinite array” that grows by itself. But it has one limitation: access to elements is by number (index). If we have a list of a thousand people and we want to find Alice’s phone number, we either need to know her index or iterate through everyone.

In real life, we often look up data by a unique attribute:

  • by name we look up a phone number,
  • by passport number we find the owner,
  • by login we find a password,
  • by ID we find an object in the database.

For this we need a data structure that can do: “got a key → immediately found the value.” In Java, that’s HashMap<K,V>.

Analogy:
Imagine a regular paper dictionary. You’re looking up the translation of “house.” You don’t need to flip through every page. You go straight to the letter “H” and find the word you need. That’s how HashMap works too: given a key (the word) we instantly get a value (the translation).

Creating a map

To create a map, you need to specify which types will be the keys and the values.

import java.util.HashMap;

HashMap<String, String> phonebook = new HashMap<String, String>();

Here:

  • String (the first type) is the key type (a person’s name).
  • String (the second type) is the value type (a phone number).

Now phonebook is like a real phonebook.

Other examples:

HashMap<String, Integer> grades = new HashMap<String, Integer>();  // name → grade
HashMap<Integer, String> users = new HashMap<Integer, String>();   // id → name
HashMap<String, Boolean> flags = new HashMap<String, Boolean>();   // key → boolean value

Unlike ArrayList, a map has no add() method, but it has its own, no less interesting ones.

2. The put(key, value) method — add a pair

The main difference between HashMap and arrays/lists is that it stores not just a set of values but key–value pairs. This makes it similar to a real dictionary: every word has a translation, every name has a phone number, every login has a password.

Example:

phonebook.put("Alice", "+380501112233");
phonebook.put("Bob", "+380671234567");

Now in our phonebook:

  • the key "Alice" is associated with the value "+10501112233",
  • the key "Bob" is associated with the value "+10671234567".

This means that to get the value (the phone number) we only need to know the key (the name).

Important: keys are unique. If we try to add a new value under an existing key, the old value will be overwritten.

phonebook.put("Alice", "+10999999999");

Now Alice has only the new number; the old number is lost.

Takeaway: put is the method for adding or updating entries. If the key is new, the entry is created. If the key already exists, the entry is updated.

3. The get(key) method — retrieve a value

To find a value, you need to know the key. This is the main trick of HashMap: key lookup is very fast—almost instantaneous—regardless of whether we have a thousand entries or a million.

Example:

System.out.println(phonebook.get("Alice"));

Output:

+10501112233

If there is no such key, get returns null:

System.out.println(phonebook.get("Charlie")); // null

This means: “the key "Charlie" is not in the map”.

4. The containsKey(key) method — check for existence

To avoid running into null, it’s useful to check first whether the key is in the map.

Example:

System.out.println(phonebook.containsKey("Charlie"));

Output:

false

This way we can decide ahead of time:

  • if the key is missing — create a new entry,
  • if the key exists — update it.

Common pattern:

if (phonebook.containsKey("Alice")) 
{
    System.out.println("Alice already has a number!");
} 
else 
{
    phonebook.put("Alice", "+10111111111");
}

5. The remove(key) method — delete an entry

Deletion is just as simple: you only need to know the key.

phonebook.remove("Bob");
System.out.println(phonebook.get("Bob"));

Output:

null

Now the entry with the key "Bob" is no longer in the map.

6. Iterating over all pairs

Often we need not only to get data by a particular key but also to print the entire map. For this we use the entrySet() method.

for (var entry : phonebook.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

Example output:

Alice -> +10501112233

In this way, we immediately get access to both the key (entry.getKey()) and the value (entry.getValue()).

7. Practice: word count

Let’s look at a classic task — counting the number of word repetitions in a text. This is one of the clearest examples of why we need a HashMap.

String text = "java java core java";
HashMap<String, Integer> freq = new HashMap<String, Integer>();

for (String w : text.split(" ")) 
{
    Integer old = freq.get(w);
    freq.put(w, (old == null) ? 1 : old + 1);
}

System.out.println(freq);

Output:

{core=1, java=3}

Let’s break down what’s happening here:

  1. We split the string "java java core java" into words.
  2. For each word, we check whether it’s already in the map (freq.get(w)).
  3. If it isn’t (null), this is the word’s first occurrence → we put 1.
  4. If it is, the word has occurred before → we increment the value by one.

Real-world applications:

  • counting API calls,
  • word-frequency statistics in a text,
  • tracking inventory quantities in a warehouse.

8. Practice: phonebook

Let’s write a slightly larger application.

import java.util.HashMap;
import java.util.Scanner;

public class PhonebookApp {
    public static void main(String[] args) 
    {
        HashMap<String, String> phonebook = new HashMap<String, String>();
        Scanner console = new Scanner(System.in);

        while (true) 
        {
            System.out.print("Enter a name (or an empty line to exit): ");
            String name = console.nextLine();
            if (name.isEmpty()) break;

            System.out.print("Enter a phone number: ");
            String phone = console.nextLine();

            phonebook.put(name, phone);
        }

        System.out.println("Phonebook:");
        for (var entry : phonebook.entrySet()) 
        {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
    }
}

The program works like a mini directory. You enter names and phone numbers; they are stored in a HashMap. At the end, you can print the entire list. Maps are used very often in real projects.

1
Task
JAVA 25 SELF, level 12, lesson 2
Locked
Adding and retrieving a value
Adding and retrieving a value
1
Task
JAVA 25 SELF, level 12, lesson 2
Locked
Check for key existence
Check for key existence
1
Task
JAVA 25 SELF, level 12, lesson 2
Locked
Removing an element from the map
Removing an element from the map
1
Task
JAVA 25 SELF, level 12, lesson 2
Locked
Word count in text
Word count in text
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION