How to Choose Between List, Set, and Map
You’re doing a library inventory. The library has two copies of The Night Library, with inventory IDs B-101 and B-102. The scanner reads B-102, then B-101, then B-102 again.
Before you read on, predict the result. How many copies should the inventory report as counted? What should appear in the scan log, and in what order?
A report that groups the scans by title gives you one. That is the number of titles, so it undercounts physical copies. A report that counts each scan gives you three. The inventory needs two counted copies and three logged scans, in the original scan order.
If you want a refresher on loops, packages and records, start with Java for Beginners in 2026: From Your First Program to Tested Business Rules.
Three questions, three collections
- What happened, and in what order? A
List<Scan>records each scan, including repeated IDs. The angle brackets are how Java writes generics. Here they tell Java that the list holdsScanobjects, so Java can check what you add and what type you get back. - Which copies have already been counted? A
Set<String>holds distinct inventory IDs. The type inside the brackets tells you each ID is a string. - Which copy belongs to this ID? A
Map<String, BookCopy>uses two type arguments.Stringis the key type, used for lookup.BookCopyis the value type, used for the catalog data returned by that lookup.
In the lab, a Scan is a record with one component, the ID read by the scanner. Each position in the log represents one event. A BookCopy record carries the ID and title, which you can read with id() and title().
public record BookCopy(String id, String title) {
}
List, Set and Map are interfaces. The interface describes the operations and their contracts. To create the collections, choose implementations. Here ArrayList supports appending events in order and allows repeated elements. HashSet stores unique members, and HashMap stores one value per key. Neither hash-based implementation promises iteration order. The empty <> on the right lets Java infer the type arguments from the declaration. Java SE 25 · List, Set, Map, ArrayList, HashSet, HashMap.
private final List<Scan> scanLog = new ArrayList<>();
private final Set<String> scannedIds = new HashSet<>();
private final Map<String, BookCopy> catalog = new HashMap<>();
Log the scan, then decide whether it counts
public ScanResult recordScan(String id) {
scanLog.add(new Scan(id));
BookCopy copy = catalog.get(id);
if (copy == null) {
return ScanResult.UNKNOWN_ID;
}
if (scannedIds.add(id)) {
return ScanResult.COUNTED;
}
return ScanResult.REPEAT;
}
Read the method from top to bottom. First, scanLog.add appends the event, so every read appears in the log. Then catalog.get(id) looks up the copy. The lab stores actual BookCopy objects in the catalog, so a null result means the ID is unknown. That path returns before updating scannedIds. The console prints UNKNOWN_ID, and the event stays in the log for review. Java SE 25 · Map.get.
With a known ID, scannedIds.add(id) returns true on the first successful insertion. If that ID is already present, it leaves the set as it was and returns false. In the three-scan sequence, the calls return true, true, then false. The final scan is recorded as an event and reported as a repeat. Java SE 25 · Set.add.
Decide what identifies a copy
A title answers “Which work is this?” An inventory ID answers “Which physical copy is this?” Both copies can share a title, and a catalog correction can change the title while the ID stays the same. Use the stable ID as the set element and map key.
HashSet uses equals and hashCode for its elements, and HashMap uses them for its keys. Equal objects must have equal hash codes. Different objects can share a hash code, so equality still matters. Two String objects with the same text represent the same inventory ID. Strings are immutable, so their contents cannot change while they are in the set or map. Java SE 25 · Object.hashCode, String.
A record’s generated equals compares all its components for two instances of the same record class. Its generated hashCode also uses all components. Two BookCopy values with the same ID and different titles therefore compare unequal. That is useful for comparing two catalog descriptions. The inventory uses the ID when deciding whether they refer to the same physical copy. Java SE 25 · Record.
Give duplicate catalog IDs a clear rule
A map has one value per key. With put, a second write to the same key replaces the first value. The small PutExample program demonstrates the replacement in a separate map.
Map<String, BookCopy> example = new HashMap<>();
example.put("B-101", new BookCopy("B-101", "The Night Library"));
BookCopy previous = example.put("B-101",
new BookCopy("B-101", "A Different Title"));
System.out.println(previous.title() + " -> " + example.get("B-101").title());
System.out.println("Catalog entries: " + example.size());
The Night Library -> A Different Title
Catalog entries: 1
For this inventory, reject any second registration with the same ID, even when the proposed record is identical. putIfAbsent keeps the existing catalog record and returns it so the program can report the duplicate with an exception. This works because the catalog only stores non-null BookCopy values. Java SE 25 · Map.put and Map.putIfAbsent.
public void addCopy(BookCopy copy) {
if (catalog.putIfAbsent(copy.id(), copy) != null) {
throw new IllegalArgumentException(
"Duplicate catalog ID: " + copy.id());
}
}
Find missing copies and control the report order
Loop over all catalog keys. For each key, use contains to ask whether that copy has been counted. Every catalog ID absent from the counted set goes into the missing list. If you scan only B-102, the missing list contains B-101.
public List<String> missingIds() {
List<String> missing = new ArrayList<>();
for (String id : catalog.keySet()) {
if (!scannedIds.contains(id)) {
missing.add(id);
}
}
missing.sort(Comparator.naturalOrder());
return missing;
}
The missing list is sorted by ID text. The program also copies counted IDs into a list and sorts that list the same way. So the report prints [B-101, B-102] even though B-102 was scanned first. The scan log uses its original append order. Java SE 25 · List.sort, Comparator.naturalOrder.
Return a snapshot of the log
public List<Scan> scanLog() {
return List.copyOf(scanLog);
}
List.copyOf gives callers an unmodifiable snapshot in scan order. They cannot add, remove or replace entries through that list. A later scan adds an entry to the inventory’s internal list, and a snapshot you already received keeps its original entries.
The snapshot holds references to the same elements. If it contained mutable objects, a caller could still change an object through a reference, and readers of the snapshot could see that change. Here Scan contains only an immutable String, so there is no mutable scan data to share. Java SE 25 · List.copyOf, Record.
Choose by the question you need to answer
| Task | Start with | What it gives you |
|---|---|---|
| Replay scans in the order they arrived | List with ArrayList |
All events and their positions |
| Check whether an ID has already been counted | Set with HashSet |
One entry per ID and a boolean from add |
| Look up a copy by its ID | Map with HashMap |
One catalog value per key |
| Report missing copies in ID order | Catalog keys, Set.contains and a sorted List |
Expected IDs that have yet to be counted |
Run the library inventory lab
Download the library inventory lab ZIP, extract it and open a terminal in the extracted folder. You need JDK 25 on your path. The lab was tested on Windows x64 with Eclipse Temurin 25.0.5.1+2. The same commands are designed for PowerShell, macOS and Linux shells. The program uses the JDK alone. Adoptium · Temurin 25.0.5.1+2.
java -version
javac -version
javac --release 25 -d out "@sources.txt"
java -cp out inventory.Main
@sources.txt passes the listed source paths to javac. -d out sends the compiled files to out, and -cp out tells Java where to find the inventory.Main class.
B-102 -> COUNTED
B-101 -> COUNTED
B-102 -> REPEAT
Scan log: [Scan[id=B-102], Scan[id=B-101], Scan[id=B-102]]
Copies counted (2): [B-101, B-102]
Missing copies: []
Now supply your own scan sequence. Predict the result for one known ID and one unknown ID before you run it.
java -cp out inventory.Main B-102 B-999
B-102 -> COUNTED
B-999 -> UNKNOWN_ID
Scan log: [Scan[id=B-102], Scan[id=B-999]]
Copies counted (1): [B-102]
Missing copies: [B-101]
Run the put counterexample and the tests with these commands.
java -cp out inventory.PutExample
java -cp out inventory.InventoryTest
The tests cover repeated scans, different copies of the same title, unknown IDs, duplicate catalog keys, missing copies, output order and log snapshots. As a final exercise, run the same known IDs in a different order. The scan log should change while the counted IDs still appear sorted.