Loading...

Java HashMap

Create a HashMap<String, String> named scores, call scores.put("oak", "leaf");, then print scores.get("oak"). Compile Desk.java and run java Desk. The screen should show one line: leaf. The key "oak" finds the value "leaf". Putting a pair and reading it back by key is what this page teaches.

A key that finds a value

On the list-methods page you reached values by slot number: get(0). A HashMap reaches a value by a key you choose. You write the pair with put. You read the value with get and the same key. There is no slot zero for this lesson’s teaching path — the key is the label.
Open Desk.java. Keep the public class name Desk so the file name matches. Delete leftover ArrayList lines, tags.get(0), tags.size(), tags.remove(0), and any Rack or Shelf demo. Those belong to the list pages. Also delete any Scanner, nextLine, or keyboard read. The program must not wait for typing.
Near the top, above public class Desk, write:
import java.util.HashMap;
That import brings the HashMap type into short-name reach. Without it, javac cannot see the short name HashMap on this page. Spell java.util and HashMap carefully. Do not invent import java.util.*; as a requirement here — one exact import is enough.
Inside main, create the map:
HashMap<String, String> scores = new HashMap<String, String>();
The first type in the angle brackets is the key kind. The second is the value kind. Both are String on this page so the demo stays with words. The name scores is the name you keep in the teaching file. The new HashMap<String, String>() call builds an empty map. At this moment it holds no pairs.

Put oak to leaf, then get oak

Call scores.put("oak", "leaf"); on its own line. The first quoted word is the key. The second quoted word is the value. Order inside put matters: key first, value second. Do not swap them in the file you keep.
Then write:
System.out.println(scores.get("oak"));
Pass the same key "oak" to get. Do not pass "leaf" as the get argument for the kept file — get asks for the key, not the value. Do not write scores.get(0) — that is the list shape from Rack, not the map shape here. Save before you compile.

Desk put then get

java
import java.util.HashMap;

public class Desk {
    public static void main(String[] args) {
        HashMap<String, String> scores = new HashMap<String, String>();
        scores.put("oak", "leaf");
        System.out.println(scores.get("oak"));
    }
}

From the folder that holds Desk.java, run javac Desk.java. When parentheses, braces, angle brackets, and semicolons match, javac writes no line of its own. Then run java Desk — not java Desk.java, and not java HashMap. Leave the .java ending off the run command. Start the class that holds main.
The program should print one line and stop: leaf. It should not ask you to type. If the terminal waits for keyboard input, a nextLine call from an older exercise is still in a file. Delete that call and keep the HashMap create, the put line, and System.out.println(scores.get("oak"));.
Walk the run once. Java starts at Desk.main. The import has already named which HashMap you mean. The new line builds an empty map. The put stores the pair oak → leaf. The call get("oak") returns leaf. The print line writes that word. The screen shows leaf. Nothing else should print. If you see oak, you printed the key by hand or used the wrong get argument. If you see 2 or [pine], you are still running a Rack size or remove demo — switch to java Desk.
If javac says it cannot find HashMap, the import line is missing, misspelled, or placed after public class Desk. Move import java.util.HashMap; above the class line. If you call get("oak") before any put, the print can show null because that key was never stored. Keep put before get on this page. If you write scores.put(oak, leaf); without quotes, javac treats the words as names that do not exist. Keep the quotes around both key and value.

Whole map print as a second look

A second Desk file prints the map object after the same put. That shows the pair shape Java uses when you print the map itself.

Desk print whole map

java
import java.util.HashMap;

public class Desk {
    public static void main(String[] args) {
        HashMap<String, String> scores = new HashMap<String, String>();
        scores.put("oak", "leaf");
        System.out.println(scores);
    }
}

Compile and run that second file the same way. The screen shows {oak=leaf} — key, equals sign, value, inside curly braces. That shape is useful to confirm the pair is inside the map. The teaching path for the quiz screen leaf is still the first file with get("oak"). Use the whole-map print only to see the stored pair. Do not mix get(0) into either Desk file — maps do not use list slot numbers on this page.
If the screen shows [] or [oak, pine], an ArrayList demo is still running. Stay with HashMap and java Desk.

Compared with list get and with put

On the list-methods page, get(0) needed a slot index after add. On this page, get("oak") needs the key string after put. A leftover Rack file that only prints tags.get(0) is a different lesson. For this page keep put("oak", "leaf") and get("oak") in Desk.
You can store more pairs with more put calls. This page keeps one pair so the key and the printed value stay easy to see. A later page — HashSet — stores unique values without a separate key-and-value pair story. Stay with HashMap put and get here.
When old Rack.java or Shelf.java files still sit nearby, leave them alone or delete them only if they confuse which class you run. Run java Desk after you compile the HashMap file from this lesson.

What this leaves for HashSet

This page opens key-and-value storage with HashMap. The next page opens a set of unique values with HashSet. Stay with put and get on the map here. Do not invent set add as a requirement on this page; the lesson goal is the key that finds the value and the screen leaf.

Before HashSet

You can import java.util.HashMap, create HashMap<String, String> scores, call scores.put("oak", "leaf");, then print scores.get("oak"). Compile Desk.java and run java Desk. The screen shows leaf. The key found the value. The next page is HashSet, where you store unique values without pairing each one to a separate key on that lesson’s path.
Keep the import above the class. Keep put before get. Keep the key "oak" the same in both calls. Those three habits are the checkpoint for this page before you move on. When the screen shows leaf after get("oak"), the HashMap did its job for this lesson and you are ready for the next topic.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top