← Back to Home

Module 2: Maps

Module Overview

Explore the Map interface and its various implementations such as HashMap, LinkedHashMap, and TreeMap.

Learning Objectives

Code Examples

Here are some examples demonstrating key Map concepts:

Creating and Using a HashMap

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

public class MapExample {
    public static void main(String[] args) {
        // Creating a new HashMap
        Map<String, Integer> studentScores = new HashMap<>();
        
        // Adding key-value pairs to the Map
        studentScores.put("Alice", 95);
        studentScores.put("Bob", 87);
        studentScores.put("Charlie", 92);
        
        // Accessing a value by key
        System.out.println("Bob's score: " + studentScores.get("Bob"));
        
        // Overwriting an existing value
        studentScores.put("Bob", 90);
        System.out.println("Bob's updated score: " + studentScores.get("Bob"));
        
        // Checking if a key exists
        System.out.println("Contains David? " + studentScores.containsKey("David"));
        System.out.println("Contains score 95? " + studentScores.containsValue(95));
        
        // Removing a key-value pair
        studentScores.remove("Charlie");
        
        // Size of the Map
        System.out.println("Number of students: " + studentScores.size());
    }
}

Iterating Over a Map

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

public class MapIterationExample {
    public static void main(String[] args) {
        Map<String, String> capitals = new HashMap<>();
        capitals.put("USA", "Washington D.C.");
        capitals.put("UK", "London");
        capitals.put("France", "Paris");
        capitals.put("Germany", "Berlin");
        
        // Using entrySet() - iterate over key-value pairs
        System.out.println("Iterating using entrySet():");
        for (Map.Entry<String, String> entry : capitals.entrySet()) {
            System.out.println(entry.getKey() + " has capital " + entry.getValue());
        }
        
        // Using keySet() - iterate over keys
        System.out.println("\nIterating using keySet():");
        for (String country : capitals.keySet()) {
            System.out.println("Country: " + country);
        }
        
        // Using values() - iterate over values
        System.out.println("\nIterating using values():");
        for (String capital : capitals.values()) {
            System.out.println("Capital: " + capital);
        }
    }
}

Using Map with Custom Objects as Keys

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

class Student {
    private int id;
    private String name;
    
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
    
    // Must override equals for objects used as Map keys
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return id == student.id;
    }
    
    // Must override hashCode for objects used as Map keys
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
    
    @Override
    public String toString() {
        return "Student{id=" + id + ", name='" + name + "'}";
    }
}

public class CustomKeyExample {
    public static void main(String[] args) {
        Map<Student, Double> studentGPA = new HashMap<>();
        
        Student alice = new Student(1001, "Alice");
        Student bob = new Student(1002, "Bob");
        
        studentGPA.put(alice, 3.85);
        studentGPA.put(bob, 3.62);
        
        // Creating another Student object with same ID as Alice
        Student aliceDuplicate = new Student(1001, "Alice Smith");
        
        // Since equals and hashCode are based on ID, this will update Alice's GPA
        studentGPA.put(aliceDuplicate, 3.90);
        
        System.out.println("Alice's GPA: " + studentGPA.get(alice));
        System.out.println("Number of entries: " + studentGPA.size());
    }
}

Resources