Back to course

Working with the Map Interface (HashMap, TreeMap)

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 39: Working with the Map Interface

A Map is a collection used to store data in key-value pairs. It provides an efficient way to retrieve a value based on its unique key.

1. Key Characteristics of Maps

  • Each key must be unique.
  • Values can be duplicates.
  • Keys are used for lookup; values are the data being stored.

2. HashMap

  • Implementation: Uses a hash table.
  • Performance: Very fast (O(1)) for put, get, and remove operations, assuming good keys.
  • Order: No guaranteed order.

java import java.util.HashMap; import java.util.Map;

// Map<Key Type, Value Type> Map<String, Integer> studentAges = new HashMap<>();

// Adding elements studentAges.put("Charlie", 22); studentAges.put("Mia", 24); studentAges.put("Ben", 22); // Values can be duplicated studentAges.put("Charlie", 23); // Key must be unique, replaces old value (22 -> 23)

// Retrieving elements System.out.println("Mia's Age: " + studentAges.get("Mia")); // Output: 24 System.out.println(studentAges.containsKey("Ben")); // true

3. Iterating a Map

Maps cannot be iterated directly. You must get one of three views:

  1. Key Set: Use map.keySet() to get a Set of all keys.
  2. Values: Use map.values() to get a Collection of all values.
  3. Entry Set: Use map.entrySet() to get a Set of Map.Entry<K, V> objects (most efficient for simultaneous access to key and value).

java for (Map.Entry<String, Integer> entry : studentAges.entrySet()) { System.out.println(entry.getKey() + " is " + entry.getValue()); }

4. TreeMap

  • Stores keys in their natural sorted order (or using a Comparator).
  • Slower than HashMap (O(log N)) but provides sorted iteration.