Maps with your own objects
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Real programs keep objects in maps: students by roll number, accounts by UPI ID, bookings by seat. The value can be any object, even a list or another map, and the key can be your own class, as long as it follows a few rules.
Look up objects by id
Use the object's id as the key and the object itself as the value, so byRoll.get("CS101") finds a student at once, with no loop over a list. Below, students are registered by roll number.
Example 1 · A student registry by roll number
import java.util.LinkedHashMap;import java.util.Map;
class Student { private final String roll; private final String name; private int marks;
Student(String roll, String name, int marks) { this.roll = roll; this.name = name; this.marks = marks; }
String getRoll() { return roll; } String getName() { return name; } int getMarks() { return marks; }
void addGraceMarks(int extra) { marks = Math.min(100, marks + extra); }}
public class RegistryDemo { static void register(Map<String, Student> byRoll, Student s) { Student existing = byRoll.putIfAbsent(s.getRoll(), s); if (existing == null) { System.out.println("Registered " + s.getName() + " as " + s.getRoll()); } else { System.out.println("Roll " + s.getRoll() + " is already taken by " + existing.getName()); } }
public static void main(String[] args) { Map<String, Student> byRoll = new LinkedHashMap<>(); register(byRoll, new Student("CS101", "Asha", 78)); register(byRoll, new Student("CS102", "Bala", 33)); register(byRoll, new Student("CS101", "Chitra", 91));
Student bala = byRoll.get("CS102"); bala.addGraceMarks(5);
for (Student s : byRoll.values()) { System.out.println(s.getRoll() + " " + s.getName() + ": " + s.getMarks()); } }}Registered Asha as CS101 Registered Bala as CS102 Roll CS101 is already taken by Asha CS101 Asha: 78 CS102 Bala: 38
What this code does
putIfAbsentadds a student only for a new roll number. ForCS101the second time, it returns Asha, the student already there, so Chitra is rejected.get("CS102")returns the sameStudentobject that is in the map.addGraceMarkschanges it in place, and the map shows 38 without anotherput.
The map stores a reference to the object, not a copy. So byRoll.get("CS101").addMarks(5) changes the student inside the map, and you do not need to put it again. To stop a second registration with the same id, use putIfAbsent: it returns the student who is already there, or null if the new one was added.
Values that are lists or maps
A nested map is a map whose values are maps, such as Map<String, Map<String, Integer>> for student, then subject, then marks. Build it with computeIfAbsent.
One key often has many values. A student has marks in many subjects: Map<String, Map<String, Integer>>, a map inside a map. Below, marks lines are read into a nested map and totalled.
Example 2 · A nested map: student → subject → marks
import java.util.Map;import java.util.TreeMap;
public class ReportCardDemo { public static void main(String[] args) { String[] results = { "Riya,Maths,88", "Arjun,Physics,72", "Riya,Physics,91", "Arjun,Maths,65", "Riya,Chemistry,79", "Arjun,Chemistry,84" };
Map<String, Map<String, Integer>> report = new TreeMap<>(); for (String line : results) { String[] p = line.split(","); int marks = Integer.parseInt(p[2]); report.computeIfAbsent(p[0], k -> new TreeMap<>()).put(p[1], marks); }
for (Map.Entry<String, Map<String, Integer>> student : report.entrySet()) { int total = 0; for (int m : student.getValue().values()) { total += m; } System.out.println(student.getKey() + " " + student.getValue() + " total " + total); } System.out.println("Riya's Physics: " + report.get("Riya").get("Physics")); }}Arjun {Chemistry=84, Maths=65, Physics=72} total 221
Riya {Chemistry=79, Maths=88, Physics=91} total 258
Riya's Physics: 91What this code does
computeIfAbsentmakes an innerTreeMapthe first time a student appears;putthen adds one subject to it.- Both levels are
TreeMaps, so students and subjects print in A-Z order. report.get("Riya").get("Physics")goes one level at a time: first the student's map, then the subject.
Build it with computeIfAbsent, as in the grouping lesson: report.computeIfAbsent(name, k -> new TreeMap<>()).put(subject, marks). Pick the inner map type for the order you want: TreeMap for A-Z subjects, LinkedHashMap for the order they were added.
Your own class as a key
A composite key is a key made of two or more values, such as a coach and a seat number. A small record is the safest way to write one, because equals and hashCode come with it.
Sometimes the key is made of two values, like a train coach S4 and seat 32. Below, a plain Seat class fails to stop a double booking, and then a record fixes it.
Example 3 · Mistake: a seat class without equals and hashCode
import java.util.HashMap;import java.util.Map;
class Seat { final String coach; final int number;
Seat(String coach, int number) { this.coach = coach; this.number = number; }}
public class DoubleBookingDemo { public static void main(String[] args) { Map<Seat, String> booked = new HashMap<>();
String[] passengers = {"Riya", "Kabir"}; for (String p : passengers) { Seat wanted = new Seat("S4", 32); if (booked.putIfAbsent(wanted, p) == null) { System.out.println(p + " booked S4-32"); } else { System.out.println(p + ": S4-32 is already taken"); } } System.out.println("Bookings: " + booked.size()); }}Riya booked S4-32 Kabir booked S4-32 Bookings: 2
What this code does
SeatusesObject'sequalsandhashCode, so twonew Seat("S4", 32)objects count as different keys.putIfAbsentnever sees a match, and the same seat is sold twice. Thefinalfields do not help: the map needsequalsandhashCode.
Example 4 · The fix: a record as the key
import java.util.HashMap;import java.util.Map;
record Seat(String coach, int number) {}
public class SeatBookingDemo { public static void main(String[] args) { Map<Seat, String> booked = new HashMap<>();
String[] passengers = {"Riya", "Kabir", "Meera"}; Seat[] wanted = {new Seat("S4", 32), new Seat("S4", 32), new Seat("S4", 33)};
for (int i = 0; i < passengers.length; i++) { if (booked.putIfAbsent(wanted[i], passengers[i]) == null) { System.out.println(passengers[i] + " booked " + wanted[i]); } else { System.out.println(passengers[i] + ": " + wanted[i] + " is already taken by " + booked.get(wanted[i])); } } System.out.println("Bookings: " + booked.size()); System.out.println("Who is in S4-33? " + booked.get(new Seat("S4", 33))); }}Riya booked Seat[coach=S4, number=32] Kabir: Seat[coach=S4, number=32] is already taken by Riya Meera booked Seat[coach=S4, number=33] Bookings: 2 Who is in S4-33? Meera
What this code does
- The record's
equalsandhashCodeuse both fields, sonew Seat("S4", 32)twice is one key. Kabir is correctly refused. - A brand-new
Seat("S4", 33)object finds Meera's booking, because equal data means an equal key. - The record's
toStringprintsSeat[coach=S4, number=32]for free.
You could join the parts into a string "S4-32", but a small class keeps them typed and clear. A key class needs correct equals and hashCode for HashMap (or Comparable / a comparator for TreeMap), and it must never change.
A record gives all of that in one line: record Seat(String coach, int number) { }. Its fields are final, and equals, hashCode and toString are written for you.
The mutable key bug
The mutable key bug is changing a key object after it was put in a map. Its hash code changes, but the entry stays in the old bucket, so get and containsKey can no longer find it.
If a key object has a setter, someone may change it after put. Below, a team is renamed while it is a key in a points table, and every lookup fails.
Example 5 · Mistake: changing a key after put
import java.util.HashMap;import java.util.Map;import java.util.Objects;
class Team { private String name;
Team(String name) { this.name = name; }
void setName(String name) { this.name = name; }
@Override public boolean equals(Object o) { return o instanceof Team t && t.name.equals(name); }
@Override public int hashCode() { return Objects.hash(name); }
@Override public String toString() { return name; }}
public class PointsTableDemo { public static void main(String[] args) { Map<Team, Integer> points = new HashMap<>(); Team chennai = new Team("Chennai"); points.put(chennai, 12);
chennai.setName("Chennai Kings");
System.out.println("Map: " + points); System.out.println("get(chennai): " + points.get(chennai)); System.out.println("get(new Team(\"Chennai\")): " + points.get(new Team("Chennai"))); System.out.println("get(new Team(\"Chennai Kings\")): " + points.get(new Team("Chennai Kings"))); }}Map: {Chennai Kings=12}
get(chennai): null
get(new Team("Chennai")): null
get(new Team("Chennai Kings")): nullWhat this code does
- The entry is still in the map, and it now prints as
Chennai Kings. But it sits in the bucket of the old name. - Every lookup fails. The new name gives a different bucket; the old name reaches the right bucket, but
equalscompares it withChennai Kingsand says no. - The fix: never change a key. Remove the old entry and
putits value under a new key object.
Even a fresh key with the old value fails, because equals now compares with the changed object. Never change a key that is inside a map. To "rename" a key, take the entry out and put it back under a new key: Integer pts = points.remove(oldKey); points.put(newKey, pts);.
Find the bug
Find the key that was changed
Each snippet loses an entry. Tap the line that causes it, then check the fix.
Rename a team that is a key in a points table.
Round 1 of 2Keep the map private
An unmodifiable view is a read-only window onto a map, made with Collections.unmodifiableMap(map). Reading works, but put and remove throw UnsupportedOperationException; later changes by the owner still show.
A class that owns a map should keep the field private. If a getter returns the map itself, any caller can put, remove or clear it. Below, a hostel returns a read-only view instead.
Example 6 · Keeping the map private
import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Map;import java.util.TreeMap;
class Hostel { private final Map<String, List<String>> rooms = new TreeMap<>(); private final int capacity;
Hostel(int capacity) { this.capacity = capacity; }
boolean allot(String room, String student) { List<String> people = rooms.computeIfAbsent(room, r -> new ArrayList<>()); if (people.size() >= capacity) { return false; } people.add(student); return true; }
Map<String, List<String>> getRooms() { return Collections.unmodifiableMap(rooms); }}
public class HostelDemo { public static void main(String[] args) { Hostel hostel = new Hostel(2); System.out.println("Riya -> G-12: " + hostel.allot("G-12", "Riya")); System.out.println("Meera -> G-12: " + hostel.allot("G-12", "Meera")); System.out.println("Asha -> G-12: " + hostel.allot("G-12", "Asha")); System.out.println("Asha -> G-14: " + hostel.allot("G-14", "Asha"));
Map<String, List<String>> view = hostel.getRooms(); System.out.println(view);
try { view.put("G-12", new ArrayList<>()); } catch (UnsupportedOperationException e) { System.out.println("Cannot change rooms from outside: " + e.getClass().getSimpleName()); } }}Riya -> G-12: true
Meera -> G-12: true
Asha -> G-12: false
Asha -> G-14: true
{G-12=[Riya, Meera], G-14=[Asha]}
Cannot change rooms from outside: UnsupportedOperationExceptionWhat this code does
- Only
allotcan add students, so the rule "at most 2 per room" always holds. getRoomsreturns a read-only view. A caller can read and print it, butputthrowsUnsupportedOperationException, which we catch here to show the message.
Collections.unmodifiableMap(map) is a read-only view: later changes made by the owner still show. Map.copyOf(map) is a read-only copy: it never changes, but it does not keep any order. For a missing key, return an empty map (Map.of()) instead of null.
Next step
Check your understanding
12 quick questions