Skip to main content
Advertisement

11.4 HashMap and TreeMap

Map is structured exactly like a real-world dictionary. Just like finding a word (Key) and reading its definition (Value), the biggest strength of Map is the ability to ** instantly look up a Value using a specific Key**.

1. HashMap

This is the most commonly used Map implementation. Keys must be unique, Values can be duplicated. Like HashSet, it also does not guarantee any particular storage order.

import java.util.HashMap;

HashMap<String, Integer> scoreMap = new HashMap<>();

// 1. put(key, value): Store data
scoreMap.put("Math", 95);
scoreMap.put("Science", 88);
scoreMap.put("English", 92);
scoreMap.put("History", 88); // Values (88) can be duplicated

// Calling put() with the same key again OVERWRITES the existing value
scoreMap.put("Math", 100);

System.out.println(scoreMap); // {Math=100, Science=88, English=92, History=88}

// 2. get(key): Retrieve a value by key
System.out.println(scoreMap.get("Science")); // 88
System.out.println(scoreMap.get("P.E.")); // null (missing key returns null)

// 3. getOrDefault(): Return a fallback value for missing keys (prevents null)
System.out.println(scoreMap.getOrDefault("P.E.", 0)); // 0

// 4. containsKey(): Check if a specific key exists
System.out.println(scoreMap.containsKey("English")); // true

// 5. remove(key): Delete a specific key-value pair
scoreMap.remove("History");
System.out.println(scoreMap.size()); // 3

Iterating Through an Entire HashMap (Using Entry)

HashMap<String, String> capitals = new HashMap<>();
capitals.put("Korea", "Seoul");
capitals.put("Japan", "Tokyo");
capitals.put("USA", "Washington D.C.");

// Iterate over key-value pairs using entrySet()
for (HashMap.Entry<String, String> entry : capitals.entrySet()) {
System.out.println("Capital of " + entry.getKey() + ": " + entry.getValue());
}

// Iterate over keys only
for (String country : capitals.keySet()) {
System.out.println(country);
}

2. TreeMap

Like TreeSet, TreeMap automatically sorts its entries by Key.

import java.util.TreeMap;

TreeMap<String, Integer> sortedMap = new TreeMap<>();
sortedMap.put("banana", 2);
sortedMap.put("apple", 5);
sortedMap.put("cherry", 1);

// Keys are automatically sorted alphabetically
System.out.println(sortedMap); // {apple=5, banana=2, cherry=1}

// First and last keys
System.out.println("First: " + sortedMap.firstKey()); // apple
System.out.println("Last: " + sortedMap.lastKey()); // cherry

With this, you have now mastered all three of Java's pillar collections (List, Set, Map)! Knowing when and how to choose among these three is more than enough to solve the vast majority of real-world data processing challenges you will encounter.

Advertisement