Java HashMap & HashSet

Key-value maps and unique sets.

✍️ 2 exercises in this lesson

HashMap

Stores key → value pairs: Map<String, Integer> ages = new HashMap<>();

  • put(), get(), getOrDefault(), containsKey(), remove(), keySet(), entrySet()

HashSet

Stores unique values: duplicates are ignored. add(), contains(), remove().

HashMap and HashSet do not keep order. Use LinkedHashMap / TreeMap when order matters.

Key Takeaways: Java HashMap & HashSet

Mastering Java HashMap & HashSet helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java HashMap & HashSet Code Example

Java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = new HashMap<>();
        stock.put("Laptop", 12);
        stock.put("Mouse", 150);
        stock.put("Laptop", 10);   // replaces the old value

        System.out.println(stock.get("Laptop"));
        System.out.println(stock.getOrDefault("Monitor", 0));
        for (Map.Entry<String, Integer> e : new TreeMap<>(stock).entrySet()) {
            System.out.println(e.getKey() + ": " + e.getValue());
        }

        Set<String> tags = new HashSet<>(List.of("java", "spring", "java"));
        System.out.println(tags.size());
    }
}
Output
10
0
Laptop: 10
Mouse: 150
2
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java HashMap & HashSet Practice Exercises

Check what you learned in “Java HashMap & HashSet”.

/ 2 solved
Fill in the blank

Read a value by key with a default.

int qty = stock.("Monitor", 0);
✓ Correct! Not quite. Try again.
Multiple choice

What does a HashSet do with duplicates?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services