SteelReed

Search

Search posts, questions…

2. Data Structures & Algorithms

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.

17 Nov 20267 min readJunior

–

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.

JAVA
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");                                  // UnsupportedOperationException

Other 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.of reject null: List.of("a", null) throws NullPointerException, and so does contains(null).
  • Map.of throws on duplicate keys; iteration order of Map.of and Set.of is unspecified, so don't write tests that rely on printed order.
  • stream().toList() returns an unmodifiable list; if you need to modify it use Collectors.toCollection(ArrayList::new).
  • Collections.unmodifiableList(list) is a view: whoever holds the original list can change it and the view sees it. List.copyOf is an independent copy.
  • Arrays.asList(...) is fixed-size and wraps the original array: set works, add doesn't.
  • computeIfAbsent(k, x -> new ArrayList<>()).add(v) replaces "get, check null, put".
  • Java 21: getFirst(), getLast(), reversed() for List, Deque, LinkedHashSet. java.util.Stack is a legacy class extending Vector: use ArrayDeque.

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, removeAll or indexOf on large Lists inside loops.
  • Classes used as keys or Set elements override both equals and hashCode (or are records).
  • No removing inside for-each; use removeIf or Iterator.remove().
  • remove on a List<Integer> does what's intended: index or value.
  • No add to results of List.of or stream().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.

JAVA
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
  1. out.contains is O(n) inside the loop: O(n²), about 1.25·10⁹ comparisons for 50,000 emails.
  2. It checks e.toLowerCase() but adds the original e: "[email protected]" is added, then "[email protected]" doesn't look like a duplicate because out holds 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; contains on a large List is O(n).
  • Default to ArrayList, HashSet, HashMap, ArrayDeque.
  • Keys and Set elements need equals and hashCode on the same fields; records do it for you.
  • Remove while iterating with removeIf; remove(int) removes by index.
  • List.of and stream().toList() are unmodifiable.

Read more: Part 3: TreeMap, Comparator, iterators.

Practice interview questions on this topic

All Collections & DSA questions →All Java Core questions →

Loading comments…