Java Collections: List, Set and Map
Why one removeAll call hangs a request for tens of seconds: choosing List, Set, Map or Queue by the operation you call most, a pick-the-collection table, equals and hashCode in a HashSet, unmodifiable collections (List.of, toList), and how to review collection code an AI wrote.
On this page
1. The problem
A sync job calls active.removeAll(cancelled) on two 100,000-element ArrayLists. Every element of active rescans all of cancelled: about 10¹⁰ comparisons, and the request hangs for tens of seconds. Wrapping it as new HashSet<>(cancelled) cuts that to about 2·10⁵.
2. Key idea
Each collection is built to answer one question fast; ask it a different one and it still answers correctly, just by scanning everything. A List is a numbered queue of people, a Set a guest list (everyone once), a Map a phone book looked up by name.
| Operation | ArrayList |
HashSet, HashMap |
TreeSet, TreeMap |
|---|---|---|---|
get(i) by position |
O(1) | n/a | n/a |
contains, get(key) |
O(n) | O(1) on average | O(log n) |
| Iteration order | insertion order | not guaranteed | ascending |
Python's list, set, dict and JavaScript's Array, Set, Map are the same: array.includes inside a loop is O(n²).
2.1 What to pick?
Declare variables by interface (List<String> x = new ArrayList<>()) so changing your mind is a one-line edit.
| Pick | Use when | Don't use when |
|---|---|---|
ArrayList |
iterating, index access, appending | you often ask "is x in here" over many elements |
HashSet |
blocklists, processed ids | you need a stable iteration order |
LinkedHashSet, LinkedHashMap |
dedup or key lookup keeping insertion order, LRU caches | you need sorting by value |
HashMap |
caches, counting, grouping by key | keys are mutable objects |
TreeSet, TreeMap |
leaderboards, nearest, ranges | you only sort once when printing |
ArrayDeque, PriorityQueue |
queues, stacks, top-k | multiple threads: BlockingQueue |
List.of, List.copyOf |
constants, values handed to callers | callers need add |
3. In Java
Most collection bugs live in four lines: equals/hashCode, removing while iterating, remove(int), and unmodifiable collections.
List<String> names = new ArrayList<>(List.of("An", "Binh", "Chi"));
names.removeIf(n -> n.startsWith("B")); // removing while iterating: correct
List<Integer> ids = new ArrayList<>(List.of(5, 1, 7));
ids.remove(1); // removes INDEX 1 -> [5, 7]
ids.remove(Integer.valueOf(7)); // removes the value 7 -> [5]
record Email(String value) {} // records generate equals/hashCode
Set<Email> emails = new HashSet<>();
emails.add(new Email("[email protected]"));
emails.add(new Email("[email protected]")); // false: size() is still 1
Map<String, Integer> counts = new HashMap<>();
counts.merge("java", 1, Integer::sum); // absent -> 1, present -> add 1
List<String> fixed = List.of("a", "b");
fixed.add("c"); // UnsupportedOperationExceptionOther languages: Go has no set, use map[K]struct{}; Node.js Set and Map compare keys with ===, so two objects with the same content are two keys.
Unmodifiable collections and commonly misused APIs
List.of,Set.of,Map.ofrejectnull:List.of("a", null)throwsNullPointerException, and so doescontains(null).Map.ofthrows on duplicate keys; iteration order ofMap.ofandSet.ofis unspecified, so don't write tests that rely on printed order.stream().toList()returns an unmodifiable list; if you need to modify it useCollectors.toCollection(ArrayList::new).Collections.unmodifiableList(list)is a view: whoever holds the originallistcan change it and the view sees it.List.copyOfis an independent copy.Arrays.asList(...)is fixed-size and wraps the original array:setworks,adddoesn't.computeIfAbsent(k, x -> new ArrayList<>()).add(v)replaces "get, checknull,put".- Java 21:
getFirst(),getLast(),reversed()forList,Deque,LinkedHashSet.java.util.Stackis a legacy class extendingVector: useArrayDeque.
4. Working with AI
Hand to AI: picking collections from a description of the operations, turning nested contains loops into a Set, generating tests for duplicates, empty input, null.
Check in AI-written code:
- No
contains,removeAllorindexOfon largeLists inside loops. - Classes used as keys or
Setelements override bothequalsandhashCode(or are records). - No removing inside for-each; use
removeIforIterator.remove(). -
removeon aList<Integer>does what's intended: index or value. - No
addto results ofList.oforstream().toList().
5. Exercises
Exercise 1: Review a dedup method
The AI wrote this, saying "removes duplicate emails, keeps order". There are 50,000 emails. Find the bugs, show how to prove them, fix it.
List<String> dedupe(List<String> emails) {
List<String> out = new ArrayList<>();
for (String e : emails) if (!out.contains(e.toLowerCase())) out.add(e);
return out;
}Solution to Exercise 1
out.containsis O(n) inside the loop: O(n²), about 1.25·10⁹ comparisons for 50,000 emails.- It checks
e.toLowerCase()but adds the originale:"[email protected]"is added, then"[email protected]"doesn't look like a duplicate becauseoutholds the upper-case version.
Test: dedupe(List.of("[email protected]", "[email protected]")) should return 1 element and returns 2. Add a 50,000-element test that measures time.
Fix: Set<String> seen = new HashSet<>(); and if (seen.add(e.toLowerCase(Locale.ROOT))) out.add(e);. Or new LinkedHashSet<>(...) if you normalise first.
Exercise 2: Read an UnsupportedOperationException incident
After the AI refactored findActiveUsers() from a for loop to users.stream().filter(...).toList(), POST /users/import returns 500 with UnsupportedOperationException at ImportService.java:58, the line active.add(newUser). Diagnose and fix.
Solution to Exercise 2
Diagnosis: stream().toList() returns an unmodifiable list; the old code used new ArrayList<>(), so add worked. The "no behaviour change" refactor changed the contract of the return value.
Fix: where you need to modify, make a copy: var active = new ArrayList<>(findActiveUsers());. Or have findActiveUsers return Collectors.toCollection(ArrayList::new) if every caller modifies it. Add a test that calls import through the path that does add.
Summary
- Pick a collection by its most frequent operation;
containson a largeListis O(n). - Default to
ArrayList,HashSet,HashMap,ArrayDeque. - Keys and
Setelements needequalsandhashCodeon the same fields; records do it for you. - Remove while iterating with
removeIf;remove(int)removes by index. List.ofandstream().toList()are unmodifiable.
Read more: Part 3: TreeMap, Comparator, iterators.
Practice interview questions on this topic
- What is in the Java Collections Framework? How do List, Set, Map and Queue differ?
- How do HashSet/HashMap, LinkedHashSet/LinkedHashMap and TreeSet/TreeMap differ, and which do you pick?
- How do getOrDefault, putIfAbsent, computeIfAbsent and merge differ?
- How do HashMap, Hashtable, synchronizedMap, ConcurrentHashMap and CopyOnWriteArrayList differ under concurrency?
- What are the equals and hashCode contracts? Why must you override hashCode when you override equals?
- How do arrays and ArrayList differ? When should you use a plain array?
Comments
Community rules