Java HashMap

</>Coding Tamilan.← Java course & curriculum
Java Masterclass · Lesson 42 / 50 · English

Java HashMap

Look up a value by its key.

Step-by-step explanationsRunnable JavaPractice + answer

Read this topic in தமிழ் ↗.

By the end of this lesson, you can…

  • Explain the key idea behind HashMap.
  • Read and run a complete example, then predict what changes.
  • Recognize the topic-specific mistake discussed below.
01 / The concept

Understand the idea

A Map associates keys with values. Each key has at most one mapped value; putting the same key again replaces its mapping. HashMap does not promise a stable iteration order, so do not infer business order from printed map entries.

02 / Step by step

Explore the details

Java HashMap

A HashMap stores items in key/value pairs, where each key maps to a specific value.

It is part of the java.util package and implements the Map interface.

Instead of accessing elements by an index (like with ArrayList), you use a key to retrieve its associated value.

A HashMap can store many different combinations, such as:

  • String keys and Integer values
  • String keys and String values

Create a HashMap

Create a HashMap object called capitalCities that will store String keys and String values:

Now you can use methods like put() to add key/value pairs, get() to retrieve a value by key, and remove() to delete an entry – all by using keys instead of index numbers.

Add Items

To add items to a HashMap, use the put() method:

Note: In the example above, if the same key (like "Norway") is added more than once, the latest value will overwrite the previous one, because keys in a HashMap must be unique.

Access an Item

To access a value in the HashMap, use the get() method and refer to its key:

Remove an Item

To remove an item, use the remove() method and refer to the key:

To remove all items, use the clear() method:

HashMap Size

To find out how many items there are, use the size() method:

Note: The size only counts unique keys. If a key is added more than once, only the latest value is kept.

Loop Through a HashMap

Loop through the items of a HashMap with a for-each loop.

Note: Use the keySet() method if you only want the keys, and use the values() method if you only want the values:

Other Types

Keys and values in a HashMap are actually objects. In the examples above, we used objects of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:

When Order Matters

In the next chapter, you will learn about TreeMap, which stores key/value pairs in sorted order by key.

The var Keyword

From Java 10, you can use the var keyword to declare a HashMap variable without writing the type twice. The compiler figures out the type from the value you assign.

This makes code shorter, but many developers still use the full type for clarity. Since var is valid Java, you may see it in other code, so it's good to know that it exists:

The Map Interface

Note: Sometimes you will see both Map and HashMap in Java code, like this:

This means the variable (capitalCities) is declared as a Map (the interface), but it stores a HashMap object (the actual map). Since HashMap implements the Map interface, this is possible.

HashMap Time Complexity

OperationAverage caseWorst caseNotes
put(key, val)O(1)O(n)O(n) only if many hash collisions
get(key)O(1)O(n)Hash collisions degrade to O(n)
containsKey(key)O(1)O(n)Same as get()
remove(key)O(1)O(n)—
Iteration (all entries)O(n)O(n)Must visit every bucket

Iterating a HashMap

Java reference fragmentJAVA
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob",   87);
scores.put("Carol", 92);

// entrySet() — iterate over key+value pairs
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    System.out.println(entry.getKey() + " → " + entry.getValue());
}

// forEach() — lambda shorthand (Java 8+)
scores.forEach((name, score) ->
    System.out.println(name + " scored " + score)
);

// getOrDefault() — safe access, no NullPointerException
int davidScore = scores.getOrDefault("David", 0);
System.out.println("David: " + davidScore);  // David: 0

It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later.

03 / Read and predict

A complete runnable example

This complete Main.java program focuses on the lesson idea. Reference fragments above may demonstrate individual statements; this example includes the imports, entry point, and supporting types it needs.

Main.java · complete runnable exampleJAVA
import java.util.HashMap;
public class Main {
    public static void main(String[] args) throws Exception {
        HashMap<String, Integer> scores = new HashMap<>();
        scores.put("Kavi", 80);
        scores.put("Malar", 90);
        scores.put("Kavi", 85);
        System.out.println(scores.get("Kavi"));
        System.out.println(scores.size());
    }
}
Predict first. Then reveal the expected output / வெளியீடு
85
2

The output shown was checked by running this complete example. Trace the executed statements in order, then compare with your run.

04 / Learn by changing

Change it. Run it. Understand it.

Load this lesson example into the editor. Change one value or statement, predict the result, then press RUN to execute Java.

Open Java editor ↗
After the editor loads, choose Load this lesson example, then press RUN.

Powered by OneCompiler. Code you run is sent to OneCompiler for execution. For Scanner examples, supply input in the editor I/O panel; for file examples, files exist in its execution environment.

05 / Your turn

Make it your own

Practice challenge

Read an absent key, then try getOrDefault with a fallback value.

Reveal the answer and reasoning / விடை

get returns null for an absent mapping here; getOrDefault("Arun", 0) returns 0.

One mistake to avoid: A null return can also mean a key explicitly maps to null. containsKey distinguishes those cases.

Your learning checkpoint

  • Explain the example without reading the output first.
  • Make the change requested in the practice task.
  • Describe why the result changed—or why compilation failed.

Ready to move on? Follow the next lesson in course order, or return to the curriculum to review a prerequisite.

Coding Tamilan · Understand the idea. Try the code. Build the habit.