Java NotesRohit’s interview study guide
Chapter 07

Collections

Lists, sets, maps and queues: which implementation to pick and what it costs, how HashMap really works, ordered and sorted maps, immutable collections, sequenced collections (Java 21), sorting with Comparator, and why iterating can throw ConcurrentModificationException. Every example was run with Java 25 (Eclipse Temurin 25.0.5.1); the JavaScript comparisons were run with Node 26.

Try it yourself. For each example, make an empty folder, save every code box in it under the name in its caption, and type the $ lines of the Terminal box in that folder. Your output should match the page. The examples are compact source files (chapter 01), which import java.util automatically.

9 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#The collections map

Added

JavaScript gives you three containers: Array, Set and Map (plus plain objects used as maps). Java gives you interfaces that say what a container does, and several implementations of each that differ in speed, ordering and memory. You declare variables with the interface and pick the implementation once, where you create it: List<String> names = new ArrayList<>();. Code that receives names only knows it's a List, so you can swap the implementation without touching it.

InterfaceWhat it isImplementations you'll useClosest in JavaScript
Listordered, indexed, duplicates allowedArrayList (the default), LinkedList (rarely)Array
Setno duplicatesHashSet (no order), LinkedHashSet (insertion order), TreeSet (sorted)Set
Mapkey → valueHashMap (no order), LinkedHashMap (insertion order), TreeMap (sorted keys)Map
Queue / Dequetake from the front; Deque adds both endsArrayDeque, PriorityQueue (smallest first)Array with push / shift

Two differences from JavaScript catch everyone. First, JavaScript's Set and Map always keep insertion order; Java's HashSet and HashMap don't. If you want JavaScript's behaviour, use LinkedHashSet and LinkedHashMap. Second, keys are compared with equals and hashCode, not by reference. A JavaScript Map compares object keys by identity, so two equal-looking arrays are two different keys. A Java HashMap asks the key itself whether it equals another, so List.of(1, 2) finds an entry stored under a different List.of(1, 2). That's why equals and hashCode matter so much in Java (chapter 03), and why records, which generate both, make good keys.

The mental model: the interface is the contract, the implementation is a data structure you chose for its costs. Most of this chapter is about those costs.

Collections.java
record Point(int x, int y) {}

void main() {
    List<String> cart = new ArrayList<>(List.of("keyboard", "mouse"));
    cart.add("mouse");
    IO.println(cart + " size " + cart.size() + ", first " + cart.get(0));

    Set<String> unique = new LinkedHashSet<>(cart);
    IO.println(unique + " has mouse: " + unique.contains("mouse"));

    Map<String, Integer> stock = new HashMap<>();
    stock.put("keyboard", 5);
    IO.println(stock.get("keyboard") + " " + stock.get("monitor") + " " + stock.getOrDefault("monitor", 0));

    Map<Point, String> grid = new HashMap<>();
    grid.put(new Point(1, 2), "treasure");
    IO.println("point key: " + grid.get(new Point(1, 2)));

    Map<List<Integer>, String> byList = new HashMap<>();
    byList.put(List.of(1, 2), "pair");
    IO.println("list key: " + byList.get(List.of(1, 2)));
}
Terminal
$ java Collections.java
[keyboard, mouse, mouse] size 3, first keyboard
[keyboard, mouse] has mouse: true
5 null 0
point key: treasure
list key: pair
collections.mjs
const cart = ["keyboard", "mouse"];
cart.push("mouse");
console.log(cart, "length", cart.length);

const unique = new Set(cart);
console.log(unique, "has mouse:", unique.has("mouse"));

const stock = new Map([["keyboard", 5]]);
console.log(stock.get("keyboard"), stock.get("monitor"), stock.get("monitor") ?? 0);

const grid = new Map();
grid.set({ x: 1, y: 2 }, "treasure");
console.log("point key:", grid.get({ x: 1, y: 2 }));

const byList = new Map();
byList.set([1, 2], "pair");
console.log("list key:", byList.get([1, 2]));
Terminal
$ node collections.mjs
[ 'keyboard', 'mouse', 'mouse' ] length 3
Set(2) { 'keyboard', 'mouse' } has mouse: true
5 undefined 0
point key: undefined
list key: undefined
What’s happening
  1. Lists look the same in both languages: an ArrayList built from List.of(…) (so it can grow), add is push, get(0) is [0], size() is length. Printing a Java collection calls its toString(), which gives [keyboard, mouse, mouse].
  2. Sets drop the duplicate mouse. LinkedHashSet keeps insertion order, like a JavaScript Set; a HashSet would also drop it but promise no order.
  3. Maps: a missing key gives null in Java and undefined in JavaScript. getOrDefault is Java's ?? 0.
  4. Object keys are where they differ. Java looks up new Point(1, 2) and finds the entry stored under a different Point(1, 2), because the record's equals and hashCode say they're equal. JavaScript compares object keys by identity, so a new { x: 1, y: 2 } is a different key and the lookup gives undefined.
  5. Same with lists as keys: Java's List.equals compares elements, so List.of(1, 2) finds "pair"; JavaScript's [1, 2] is a new array and finds nothing. In JavaScript you'd use a string key like "1,2"; in Java you use a record or a list.
AdvancedThe Map methods added in Java 8

If you learned Java before 8, you wrote if (map.containsKey(k)) { … } else { … } everywhere. Java 8 added methods that do the check and the update in one call. These four cover nearly every case:

Counts.java
void main() {
    var words = List.of("to", "be", "or", "not", "to", "be");

    Map<String, Integer> counts = new TreeMap<>();
    for (String w : words) {
        counts.merge(w, 1, Integer::sum);
    }
    IO.println("merge: " + counts);

    Map<Integer, List<String>> byLength = new TreeMap<>();
    for (String w : words) {
        byLength.computeIfAbsent(w.length(), k -> new ArrayList<>()).add(w);
    }
    IO.println("computeIfAbsent: " + byLength);

    counts.putIfAbsent("to", 100);
    counts.putIfAbsent("question", 0);
    IO.println("putIfAbsent: " + counts);

    counts.replaceAll((word, n) -> n * 10);
    IO.println("replaceAll: " + counts);
}
Terminal
$ java Counts.java
merge: {be=2, not=1, or=1, to=2}
computeIfAbsent: {2=[to, be, or, to, be], 3=[not]}
putIfAbsent: {be=2, not=1, or=1, question=0, to=2}
replaceAll: {be=20, not=10, or=10, question=0, to=20}
What’s happening
  1. merge(w, 1, Integer::sum) means "put 1 if the key is new, otherwise combine the old value and 1 with Integer::sum". It's the one-line word count: to goes 1 → 2, be 1 → 2. A TreeMap keeps the printout sorted by key.
  2. computeIfAbsent(key, k -> new ArrayList<>()) returns the existing list for the key, or creates, stores and returns a new one. Then .add(w) adds to it: the standard "group into lists" idiom. Note to and be appear twice in the length-2 list, because the input has them twice.
  3. putIfAbsent only writes when the key is missing: to keeps 2, and question is added with 0.
  4. replaceAll rewrites every value from its key and value.
  5. All four arrived in Java 8 (as did getOrDefault, compute and forEach). Chapter 08's Collectors.groupingBy does the grouping with streams.
AdvancedLegacy classes to avoid

Vector, Hashtable and Stack are from Java 1.0, before the collections framework (Java 1.2). Every method is synchronized, which costs time and still doesn't make compound actions ("check, then put") safe. You'll see them in old code; in new code use ArrayList, HashMap and ArrayDeque, and for real multi-threaded use the concurrent collections (chapter 09).

#ArrayList, LinkedList and ArrayDeque

Added

ArrayList is a growable array, like a JavaScript array: an Object[] plus a count. Reading get(i) is a single array access. Adding at the end is fast because the array has spare room; when it's full, ArrayList allocates a bigger one (1.5 times the size, in the JDK 25 source) and copies, which is rare enough that adding is amortised O(1). Inserting or removing in the middle shifts everything after it.

LinkedList is a doubly linked list: one node object per element, each pointing to the next and previous. Adding or removing at either end is O(1), but get(i) must walk node by node from the nearer end, so it's O(n), and every element costs an extra object. ArrayDeque is a circular array with O(1) operations at both ends; its own documentation says it's "likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue".

OperationArrayListLinkedListArrayDeque
get(i)O(1)O(n)not offered
add / remove at the endamortised O(1)O(1)O(1)
add / remove at the frontO(n)O(1)O(1)
insert in the middleO(n)O(n) to find the spotnot offered
memory per elementone referencea node objectone reference

The mental model: an ArrayList is a row of numbered boxes; a LinkedList is a treasure hunt where each clue tells you where the next one is. Modern CPUs love rows of boxes (caches load neighbours together), so even the "middle insert" case that LinkedList should win often goes to ArrayList in practice. Use ArrayList for lists, ArrayDeque for stacks and queues, and LinkedList almost never.

Brackets.java
boolean balanced(String text) {
    Deque<Character> stack = new ArrayDeque<>();
    for (char c : text.toCharArray()) {
        switch (c) {
            case '(', '[', '{' -> stack.push(c);
            case ')', ']', '}' -> {
                if (stack.isEmpty()) return false;
                char open = stack.pop();
                if ("([{".indexOf(open) != ")]}".indexOf(c)) return false;
            }
            default -> { }
        }
    }
    return stack.isEmpty();
}

void main() {
    IO.println(balanced("f(a[1], {b: 2})") + " " + balanced("f(a[1)]") + " " + balanced("(("));

    Deque<String> queue = new ArrayDeque<>();
    queue.offer("first");
    queue.offer("second");
    queue.offer("third");
    IO.println(queue.poll() + ", then " + queue.peek() + ", left " + queue);

    try {
        queue.offer(null);
    } catch (NullPointerException e) {
        IO.println("ArrayDeque rejects null");
    }
}
Terminal
$ java Brackets.java
true false false
first, then second, left [second, third]
ArrayDeque rejects null
What’s happening
  1. As a stack: push adds to the front and pop removes from the front, so the last bracket opened is the first one checked. For f(a[1], {b: 2}) the stack goes ( → ([ → ( → ({ → ( → empty, every closer matches its opener, and the result is true.
  2. In f(a[1)], after [ is pushed, the next closer is ). pop gives [, whose position in "([{" (1) differs from )'s position in ")]}" (0), so it returns false. (( ends with two openers left on the stack: false.
  3. As a queue: offer adds at the back, poll removes from the front and peek looks without removing. poll gives first, peek shows second, and [second, third] are left.
  4. ArrayDeque refuses null with a NullPointerException: null is what poll and peek return for "empty", so storing it would be ambiguous.
  5. This replaces the Java 1.0 Stack class (synchronized, and it extends Vector, so it even lets you insert in the middle of a stack). Declare the variable as Deque and you get both the stack methods and the queue methods.
AdvancedWatching an ArrayList grow

An ArrayList's capacity (the length of its hidden array) isn't public, but reflection can read it if you open java.util to your code for that run, with --add-opens. Never do this in real code; it's a way to see the growth rule for yourself.

Grow.java
int capacity(ArrayList<?> list) throws Exception {
    var field = ArrayList.class.getDeclaredField("elementData");
    field.setAccessible(true);
    return ((Object[]) field.get(list)).length;
}

void main() throws Exception {
    var list = new ArrayList<Integer>();
    IO.println("empty: capacity " + capacity(list));
    int last = 0;
    for (int i = 1; i <= 100; i++) {
        list.add(i);
        if (capacity(list) != last) {
            last = capacity(list);
            IO.println("size " + i + ": capacity " + last);
        }
    }
}
Terminal
$ java --add-opens java.base/java.util=ALL-UNNAMED Grow.java
empty: capacity 0
size 1: capacity 10
size 11: capacity 15
size 16: capacity 22
size 23: capacity 33
size 34: capacity 49
size 50: capacity 73
size 74: capacity 109
What’s happening
  1. A new ArrayList has capacity 0: it shares an empty array and allocates only on the first add.
  2. The first add allocates 10 slots (DEFAULT_CAPACITY in the source). Elements 2 to 10 fit without copying.
  3. Adding the 11th grows it to 15, then 22, 33, 49, 73, 109: each time old + old / 2, so 1.5 times. Each growth copies the array, but they get rarer as the list grows, which is why add is amortised constant time.
  4. If you know the size up front, new ArrayList<>(1000) allocates once. The --add-opens flag is needed because the JDK's internals are closed to reflection by default.
AdvancedLinkedList.get(i) in a loop

The classic way to make LinkedList slow is to index into it in a loop, which turns an O(n) loop into O(n²). This prints a stable conclusion rather than timings, because times vary from machine to machine.

Walk.java
long sumByIndex(List<Integer> list) {
    long sum = 0;
    for (int i = 0; i < list.size(); i++) sum += list.get(i);
    return sum;
}

void main() {
    int n = 50_000;
    var array = new ArrayList<Integer>();
    var linked = new LinkedList<Integer>();
    for (int i = 0; i < n; i++) {
        array.add(i);
        linked.add(i);
    }
    long t0 = System.nanoTime();
    long a = sumByIndex(array);
    long t1 = System.nanoTime();
    long b = sumByIndex(linked);
    long t2 = System.nanoTime();
    IO.println("same sum: " + (a == b));
    IO.println("LinkedList at least 10x slower: " + ((t2 - t1) > 10 * (t1 - t0)));
}
Terminal
$ java Walk.java
same sum: true
LinkedList at least 10x slower: true
What’s happening
  1. Both lists hold 0 to 49,999, and both loops compute the same sum.
  2. For the ArrayList, each get(i) is one array read: 50,000 steps in all.
  3. For the LinkedList, get(i) walks from the nearer end, up to 25,000 nodes each time: around 625 million node hops in all. It's not a little slower; it's a different complexity class, and the run shows it's at least ten times slower (in practice far more).
  4. A for-each loop (for (int x : linked)) uses the list's iterator and is O(n) on both. The trap is only indexed access, which is easy to write by accident when a method receives a List and doesn't know which kind.
What does this print? (remove on a List of Integer)
Java
void main() {
    List<Integer> ids = new ArrayList<>(List.of(10, 20, 1, 30));
    ids.remove(1);
    IO.println(ids);
    ids.remove(Integer.valueOf(1));
    IO.println(ids);
}
Show answer
Remove.java
void main() {
    List<Integer> ids = new ArrayList<>(List.of(10, 20, 1, 30));
    ids.remove(1);
    IO.println(ids);
    ids.remove(Integer.valueOf(1));
    IO.println(ids);
}
Terminal
$ java Remove.java
[10, 1, 30]
[10, 30]
What’s happening
  1. List has two remove methods: remove(int index) and remove(Object o). With the argument 1, an int, the compiler picks remove(int) because it matches exactly, without boxing.
  2. So ids.remove(1) removes the element at index 1, which is 20: [10, 1, 30].
  3. ids.remove(Integer.valueOf(1)) passes an Integer object, so remove(Object) runs and removes the element equal to 1: [10, 30].
  4. This only bites with List<Integer>, and it's a favourite interview trick. When you mean the value, box it explicitly.

#How HashMap works

Added

A HashMap is an array of buckets. To store a key, it calls the key's hashCode(), mixes the bits (in the JDK source: h ^ (h >>> 16), so the high bits affect the result too), and keeps the low bits to pick a bucket: with 16 buckets, hash & 15. Inside a bucket, it compares the stored hash and then calls equals to find the exact key. So hashCode decides which bucket, equals decides which entry in it. If two keys land in the same bucket (a collision), both are kept there, in a small linked list.

Three more facts from the JDK 25 source (HashMap.java) and its documentation, which together answer most interview questions:

  • Resizing. The bucket array starts at 16 (allocated on the first put). When the number of entries exceeds capacity × load factor (0.75), the map doubles the array and redistributes the entries.
  • Treeified buckets (Java 8). If one bucket's list grows past 8 entries, it turns into a small red-black tree, so a bucket with many collisions costs O(log n) to search instead of O(n). But only when the table has at least 64 buckets; below that, the map resizes instead, since spreading the keys out is cheaper.
  • null is allowed as one key and as values (unlike TreeMap, ConcurrentHashMap and Map.of). HashSet is a HashMap underneath: its elements are the keys.

The mental model: a coat check with numbered hooks. The hash code tells the attendant which hook; when several coats hang on one hook, they check each ticket (equals). If you change the ticket after handing the coat in, the attendant goes to the wrong hook. That's the mutable key problem, and it's the most important practical lesson here.

Buckets.java
record Collider(String name) {
    @Override
    public int hashCode() {
        return 42;
    }
}

class Sku {
    String code;

    Sku(String code) { this.code = code; }

    @Override
    public boolean equals(Object o) { return o instanceof Sku other && other.code.equals(code); }

    @Override
    public int hashCode() { return code.hashCode(); }

    @Override
    public String toString() { return code; }
}

void main() {
    var colliders = new HashMap<Collider, Integer>();
    colliders.put(new Collider("a"), 1);
    colliders.put(new Collider("b"), 2);
    colliders.put(new Collider("c"), 3);
    IO.println("hash codes: " + new Collider("a").hashCode() + " " + new Collider("b").hashCode());
    IO.println("get b: " + colliders.get(new Collider("b")) + ", size " + colliders.size());

    var prices = new HashMap<Sku, Integer>();
    var key = new Sku("KB-1");
    prices.put(key, 49);
    key.code = "KB-2";
    IO.println("get(key): " + prices.get(key));
    IO.println("get(new Sku(\"KB-1\")): " + prices.get(new Sku("KB-1")));
    IO.println("map still holds: " + prices + ", size " + prices.size());
}
Terminal
$ java Buckets.java
hash codes: 42 42
get b: 2, size 3
get(key): null
get(new Sku("KB-1")): null
map still holds: {KB-2=49}, size 1
What’s happening
  1. Every Collider has hash code 42, so all three land in the same bucket. That's legal, just slow: the map keeps them in one chain.
  2. get(new Collider("b")) goes to that bucket, finds three entries with hash 42, and calls equals on each until the record's generated equals matches name = "b". It returns 2. Collisions cost speed, never correctness, as long as equals is right.
  3. Sku is a mutable key: its hashCode comes from code. The entry is stored with the hash of "KB-1", in that hash's bucket.
  4. Then key.code becomes "KB-2". get(key) computes the hash of "KB-2", looks in a different bucket (or compares against the stored old hash) and finds nothing: null, even though it's the very same object.
  5. get(new Sku("KB-1")) has the right hash and goes to the right bucket, but equals now compares "KB-1" with the stored key, whose code is "KB-2": null again.
  6. The entry is still in the map ({KB-2=49}, size 1) but unreachable by any key: a quiet memory leak and a lost update. The fix is to use immutable keys: a String, a record of immutable fields, an enum.
AdvancedLooking inside: resizing and treeifying

You can watch the rules above happen by reading the map's private bucket array with reflection (opened with --add-opens for this run only). The first loop adds 100 well-spread Integer keys; the second adds keys that all collide.

Inside.java
record Collider(String name) {
    @Override
    public int hashCode() {
        return 42;
    }
}

Object[] table(HashMap<?, ?> map) throws Exception {
    var field = HashMap.class.getDeclaredField("table");
    field.setAccessible(true);
    return (Object[]) field.get(map);
}

int buckets(HashMap<?, ?> map) throws Exception {
    Object[] t = table(map);
    return t == null ? 0 : t.length;
}

void main() throws Exception {
    var map = new HashMap<Integer, String>();
    IO.println("new map: " + buckets(map) + " buckets");
    for (int i = 1; i <= 100; i++) {
        int before = buckets(map);
        map.put(i, "v" + i);
        if (buckets(map) != before) IO.println("entry " + i + ": " + buckets(map) + " buckets");
    }

    var bad = new HashMap<Collider, Integer>();
    for (int i = 1; i <= 11; i++) {
        bad.put(new Collider("k" + i), i);
        Object[] t = table(bad);
        Object bucket = t[(t.length - 1) & (42 ^ (42 >>> 16))];
        IO.println(i + " colliding keys: " + t.length + " buckets, bucket holds " + bucket.getClass().getSimpleName());
    }
}
Terminal
$ java --add-opens java.base/java.util=ALL-UNNAMED Inside.java
new map: 0 buckets
entry 1: 16 buckets
entry 13: 32 buckets
entry 25: 64 buckets
entry 49: 128 buckets
entry 97: 256 buckets
1 colliding keys: 16 buckets, bucket holds Node
2 colliding keys: 16 buckets, bucket holds Node
3 colliding keys: 16 buckets, bucket holds Node
4 colliding keys: 16 buckets, bucket holds Node
5 colliding keys: 16 buckets, bucket holds Node
6 colliding keys: 16 buckets, bucket holds Node
7 colliding keys: 16 buckets, bucket holds Node
8 colliding keys: 16 buckets, bucket holds Node
9 colliding keys: 32 buckets, bucket holds Node
10 colliding keys: 64 buckets, bucket holds Node
11 colliding keys: 64 buckets, bucket holds TreeNode
What’s happening
  1. A new HashMap has no bucket array at all (0); the first put allocates 16.
  2. With 16 buckets the threshold is 16 × 0.75 = 12, so entry 13 triggers a resize to 32. Then 32 × 0.75 = 24, so entry 25 resizes to 64; entry 49 to 128; entry 97 to 256. Each resize doubles the array and moves every entry, which is why HashMap.newHashMap(n) (Java 19) exists for when you know the size up front.
  3. The colliding keys all go to one bucket. Up to 8 entries it's a chain of plain Nodes.
  4. The 9th entry makes the chain longer than 8, but the table has only 16 buckets (below 64), so the map resizes instead of building a tree: 32 buckets. The 10th resizes again, to 64. Resizing can't help here (every key still hashes to 42), but the map doesn't know that.
  5. At the 11th entry the table has 64 buckets, so the bucket is treeified: it now holds a TreeNode, a red-black tree. That's the Java 8 change that keeps a flood of colliding keys from turning lookups into a linear scan.
AdvancedHashSet order isn't insertion order

Because elements are stored by bucket, a HashSet iterates in bucket order, which looks random and can change when the set resizes. JavaScript developers expect insertion order and get surprised.

Order.java
void main() {
    var words = List.of("banana", "apple", "cherry", "date", "elderberry", "fig");
    IO.println("HashSet:       " + new HashSet<>(words));
    IO.println("LinkedHashSet: " + new LinkedHashSet<>(words));
    IO.println("TreeSet:       " + new TreeSet<>(words));
}
Terminal
$ java Order.java
HashSet:       [banana, date, apple, cherry, fig, elderberry]
LinkedHashSet: [banana, apple, cherry, date, elderberry, fig]
TreeSet:       [apple, banana, cherry, date, elderberry, fig]
What’s happening
  1. HashSet prints in bucket order, decided by each string's hash code: nothing to do with the order they were added.
  2. LinkedHashSet threads a linked list through its entries, so it iterates in insertion order, exactly like a JavaScript Set.
  3. TreeSet keeps its elements sorted (alphabetically, for strings).
  4. String.hashCode() is specified by the language, so the HashSet order above is the same on every run of this JDK, but the documentation promises nothing ("no guarantees as to the order"). Code that depends on it is a bug waiting for a resize or a JDK upgrade.
What does this print? (equals without hashCode)
Java
class Tag {
    final String name;
    Tag(String name) { this.name = name; }

    @Override
    public boolean equals(Object o) {
        return o instanceof Tag t && t.name.equals(name);
    }
}

void main() {
    var tags = new HashSet<Tag>();
    tags.add(new Tag("java"));
    tags.add(new Tag("java"));
    IO.println(new Tag("java").equals(new Tag("java")) + " " + tags.size() + " " + tags.contains(new Tag("java")));
}
Show answer
Tags.java
class Tag {
    final String name;
    Tag(String name) { this.name = name; }

    @Override
    public boolean equals(Object o) {
        return o instanceof Tag t && t.name.equals(name);
    }
}

void main() {
    var tags = new HashSet<Tag>();
    tags.add(new Tag("java"));
    tags.add(new Tag("java"));
    IO.println(new Tag("java").equals(new Tag("java")) + " " + tags.size() + " " + tags.contains(new Tag("java")));
}
Terminal
$ java Tags.java
true 2 false
What’s happening
  1. equals is overridden, so two Tag("java") objects are equal: true.
  2. hashCode isn't, so each object keeps Object's identity-based hash code, which is different for every object. The second add hashes to a different value, never compares with the first, and is added: size 2, duplicates in a Set.
  3. contains(new Tag("java")) computes yet another identity hash and finds nothing: false.
  4. This is the equals/hashCode contract: equal objects must have equal hash codes. Override both or neither; a record does both for you.

#LinkedHashMap, TreeMap and sorted collections

Added

LinkedHashMap is a HashMap with a doubly linked list running through its entries. It costs a little more memory and gives you a predictable order: insertion order by default, or access order if you ask for it, where every get or put moves that entry to the end. Access order plus one overridable method, removeEldestEntry, is a complete LRU cache (least recently used is evicted first), and writing one is a common interview exercise.

TreeMap (and TreeSet, its set version) keeps keys sorted, by their natural order or by a Comparator you pass in. It's a red-black tree, so get, put and remove are guaranteed O(log n) rather than HashMap's average O(1). What you get for that is navigation: the first and last key, the greatest key at or below a value (floorKey), the smallest at or above (ceilingKey), and views of a range (headMap, tailMap, subMap). JavaScript has no sorted map at all; you'd sort an array of keys each time or use a library.

The mental model: HashMap is a pile of index cards you can find instantly; LinkedHashMap is the same pile with a string tied through them in the order you touched them; TreeMap is a card box kept in alphabetical order, slower to file into but easy to flip through by range.

Lru.java
class LruCache<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;

    LruCache(int capacity) {
        super(16, 0.75f, true);
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;
    }
}

void main() {
    var cache = new LruCache<String, String>(3);
    cache.put("/home", "home page");
    cache.put("/about", "about page");
    cache.put("/shop", "shop page");
    IO.println(cache.keySet());

    cache.get("/home");
    IO.println("after get /home: " + cache.keySet());

    cache.put("/cart", "cart page");
    IO.println("after put /cart: " + cache.keySet());
    IO.println("/about cached: " + cache.containsKey("/about"));
}
Terminal
$ java Lru.java
[/home, /about, /shop]
after get /home: [/about, /shop, /home]
after put /cart: [/shop, /home, /cart]
/about cached: false
What’s happening
  1. super(16, 0.75f, true) calls the LinkedHashMap constructor whose third argument is accessOrder: true means iteration goes from least recently used to most recently used.
  2. removeEldestEntry is called by put after every insertion. Returning true tells the map to remove its eldest entry, the first in iteration order. Here that happens when the size goes over 3.
  3. After three puts the order is [/home, /about, /shop]. get("/home") counts as an access and moves /home to the end: [/about, /shop, /home].
  4. put("/cart") makes the size 4, so removeEldestEntry returns true and the eldest, /about, is evicted: [/shop, /home, /cart].
  5. containsKey is not an access (the documentation lists the methods that are: get, put, getOrDefault, compute…, merge and a few more), so checking doesn't change the order. That's the whole LRU cache: about ten lines, because LinkedHashMap already does the bookkeeping.
AdvancedTreeMap navigation

A typical use: a price table where the answer depends on which band a value falls in. With a TreeMap, "which band?" is one call.

Shipping.java
void main() {
    TreeMap<Integer, String> rateByWeight = new TreeMap<>();
    rateByWeight.put(0, "small: 3.50");
    rateByWeight.put(2_000, "medium: 6.90");
    rateByWeight.put(10_000, "large: 14.00");
    rateByWeight.put(30_000, "freight: quote");

    for (int grams : List.of(450, 2_000, 9_999, 45_000)) {
        IO.println(grams + " g -> " + rateByWeight.floorEntry(grams).getValue());
    }

    IO.println("first band: " + rateByWeight.firstKey() + ", last band: " + rateByWeight.lastKey());
    IO.println("next band above 2500 g starts at " + rateByWeight.ceilingKey(2_500));
    IO.println("bands below 10000: " + rateByWeight.headMap(10_000));
    IO.println("bands from 2000 to 30000: " + rateByWeight.subMap(2_000, true, 30_000, true).keySet());
    IO.println("descending: " + rateByWeight.descendingMap().keySet());
}
Terminal
$ java Shipping.java
450 g -> small: 3.50
2000 g -> medium: 6.90
9999 g -> medium: 6.90
45000 g -> freight: quote
first band: 0, last band: 30000
next band above 2500 g starts at 10000
bands below 10000: {0=small: 3.50, 2000=medium: 6.90}
bands from 2000 to 30000: [2000, 10000, 30000]
descending: [30000, 10000, 2000, 0]
What’s happening
  1. The keys are band starts in grams, kept sorted by the tree whatever order they're added in.
  2. floorEntry(grams) returns the entry with the greatest key at or below grams: 450 g falls in the band starting at 0, 2,000 g exactly hits the medium band, 9,999 g is still medium, and 45,000 g is freight.
  3. firstKey and lastKey are the ends; ceilingKey(2_500) is the smallest key at or above 2,500, which is 10000.
  4. headMap(10_000) is the part of the map below 10,000 (exclusive); subMap(2_000, true, 30_000, true) takes a range with both ends included. These are views, not copies: writing to them writes to the map.
  5. descendingMap() is a reverse-order view. With a HashMap you'd need to sort the keys yourself for each of these questions.

#Immutable and unmodifiable collections

Added

Java has two different things that sound alike. Unmodifiable views (Collections.unmodifiableList(list), since Java 1.2) wrap an existing collection and refuse changes through the wrapper, but the collection underneath can still change, and the view shows those changes. Immutable collections (List.of, Set.of, Map.of from Java 9, and List.copyOf and friends from Java 10) are their own objects that nobody can change. On both, every change method (add, remove, set, put) throws UnsupportedOperationException at run time.

That last part is where Java differs from TypeScript. TypeScript's readonly string[] and ReadonlyMap are checked at compile time and erased at run time. Java's List interface has add whether or not the list supports it, so the compiler can't help: you find out when the code runs. JavaScript's Object.freeze is the closer cousin (enforced at run time, and shallow), except that a frozen array silently ignores writes outside strict mode while Java always throws.

The mental model: an unmodifiable view is a shop window: you can't reach the goods, but the shop can rearrange them. An immutable list is a photograph: it shows what was there when it was taken, forever. Both are shallow: a List.of holding mutable objects doesn't make those objects immutable.

Frozen.java
void attempt(String label, Runnable action) {
    try {
        action.run();
        IO.println(label + ": ok");
    } catch (RuntimeException e) {
        IO.println(label + ": " + e.getClass().getSimpleName());
    }
}

void main() {
    List<String> backing = new ArrayList<>(List.of("a", "b"));
    List<String> view = Collections.unmodifiableList(backing);
    List<String> copy = List.copyOf(backing);

    attempt("view.add", () -> view.add("c"));
    attempt("copy.add", () -> copy.add("c"));

    backing.add("c");
    IO.println("backing " + backing + ", view " + view + ", copy " + copy);

    List<Integer> fixed = Arrays.asList(1, 2, 3);
    attempt("asList.set", () -> fixed.set(0, 99));
    attempt("asList.add", () -> fixed.add(4));
    IO.println("asList after set: " + fixed);

    List<Integer> collected = Stream.of(3, 1, 2).sorted().toList();
    attempt("stream toList().add", () -> collected.add(4));
}
Terminal
$ java Frozen.java
view.add: UnsupportedOperationException
copy.add: UnsupportedOperationException
backing [a, b, c], view [a, b, c], copy [a, b]
asList.set: ok
asList.add: UnsupportedOperationException
asList after set: [99, 2, 3]
stream toList().add: UnsupportedOperationException
What’s happening
  1. view wraps backing; copy is an independent immutable list holding the same two elements.
  2. Both add calls compile (the type is just List<String>) and both throw UnsupportedOperationException when they run.
  3. Then backing.add("c") changes the original list. The view shows [a, b, c], because it's a window onto backing; the copy still shows [a, b]. Return List.copyOf(field) when you want callers to get a snapshot they can't change and that can't change under them.
  4. Arrays.asList is a third kind: a fixed-size list backed by the array. set works (it writes to the array), add throws, because the array can't grow.
  5. Stream.toList() (Java 16) returns an unmodifiable list too. collect(Collectors.toList()), the older form, happens to return an ArrayList today, but its documentation doesn't promise that.
AdvancedNulls, duplicates and Map.of

The Java 9 factories are strict on purpose: no null elements, keys or values, and no duplicate set elements or map keys. The checks happen when you create the collection, so the mistake shows up where it was made.

Strict.java
void attempt(String label, Runnable action) {
    try {
        action.run();
        IO.println(label + ": ok");
    } catch (RuntimeException e) {
        IO.println(label + ": " + e.getClass().getSimpleName() + (e.getMessage() == null ? "" : " (" + e.getMessage() + ")"));
    }
}

void main() {
    attempt("List.of with null", () -> List.of("a", null));
    attempt("List.of contains(null)", () -> List.of("a").contains(null));
    attempt("Set.of duplicate", () -> Set.of("a", "a"));
    attempt("Map.of duplicate key", () -> Map.of("k", 1, "k", 2));
    attempt("ArrayList contains(null)", () -> new ArrayList<>(List.of("a")).contains(null));

    var prices = Map.ofEntries(Map.entry("keyboard", 49), Map.entry("mouse", 19));
    IO.println("keyboard costs " + prices.get("keyboard"));
}
Terminal
$ java Strict.java
List.of with null: NullPointerException
List.of contains(null): NullPointerException
Set.of duplicate: IllegalArgumentException (duplicate element: a)
Map.of duplicate key: IllegalArgumentException (duplicate key: k)
ArrayList contains(null): ok
keyboard costs 49
What’s happening
  1. List.of("a", null) throws NullPointerException at creation.
  2. Even asking whether it contains null throws: the immutable lists don't allow null, and the List contract lets such lists throw on contains(null). An ArrayList just answers false, so code that worked with an ArrayList can break when someone switches to List.of.
  3. Set.of("a", "a") and Map.of with a repeated key throw IllegalArgumentException naming the duplicate: in a set literal, a duplicate is almost certainly a typo.
  4. Map.of takes up to 10 key-value pairs as arguments; for more, Map.ofEntries(Map.entry(…), …) takes any number.
  5. One more rule from the documentation: the iteration order of Set.of and Map.of is unspecified and "subject to change". In the JDK source it's randomised with a seed taken at JVM start, so it can differ between two runs of the same program. Never print one and expect a stable order; use List.of, or sort.
AdvancedImmutable records need copied lists

A record's fields are final, but final only fixes the reference. A record holding a caller's ArrayList can still change when the caller changes that list. The fix is a compact constructor that copies it.

Order.java
record Order(String id, List<String> items) {
    Order {
        items = List.copyOf(items);
    }
}

record LeakyOrder(String id, List<String> items) {}

void main() {
    var items = new ArrayList<>(List.of("keyboard"));
    var safe = new Order("o-1", items);
    var leaky = new LeakyOrder("o-2", items);

    items.add("mouse");
    IO.println(safe);
    IO.println(leaky);
}
Terminal
$ java Order.java
Order[id=o-1, items=[keyboard]]
LeakyOrder[id=o-2, items=[keyboard, mouse]]
What’s happening
  1. Both records receive the same mutable items list.
  2. Order's compact constructor replaces the parameter with List.copyOf(items) before the field is assigned, so the record holds its own immutable snapshot.
  3. LeakyOrder stores the caller's list itself.
  4. After items.add("mouse"), Order still shows [keyboard], while LeakyOrder shows [keyboard, mouse]: its "immutable" data changed under it. Records are shallowly immutable; copy collections in the compact constructor (chapter 03).
What does this print? (List.of and add)
Java
void main() {
    List<String> names = List.of("ana", "rohit");
    try {
        names.add("maya");
    } catch (UnsupportedOperationException e) {
        IO.println("can't add: " + e.getMessage());
    }
    IO.println(names);
}
Show answer
Names.java
void main() {
    List<String> names = List.of("ana", "rohit");
    try {
        names.add("maya");
    } catch (UnsupportedOperationException e) {
        IO.println("can't add: " + e.getMessage());
    }
    IO.println(names);
}
Terminal
$ java Names.java
can't add: null
[ana, rohit]
What’s happening
  1. List.of returns an immutable list, but its type is plain List<String>, so names.add("maya") compiles.
  2. At run time add throws UnsupportedOperationException. Its message is null: the immutable collections don't explain themselves, which is why the class name is what you'll recognise in a log.
  3. The list is unchanged: [ana, rohit]. If you need to add, start from new ArrayList<>(List.of(…)).

#Sequenced collections

Added

Before Java 21, "give me the last element" depended on which collection you had: list.get(list.size() - 1) for a List, deque.getLast() for a Deque, sortedSet.last() for a SortedSet, and for a LinkedHashSet, which has an order, no way at all short of iterating to the end. Java 21 added three interfaces (JEP 431) that give every collection with a defined order the same methods:

  • SequencedCollection (implemented by List, Deque, LinkedHashSet, TreeSet): getFirst, getLast, addFirst, addLast, removeFirst, removeLast, reversed.
  • SequencedSet: the same, for sets.
  • SequencedMap (implemented by LinkedHashMap, TreeMap): firstEntry, lastEntry, pollFirstEntry, pollLastEntry, putFirst, putLast, reversed, and sequencedKeySet / sequencedValues / sequencedEntrySet.

The mental model: if a collection has a first and a last element, it now has methods called first and last. JavaScript developers will recognise arr.at(-1), with one difference: on an empty collection, getFirst and getLast throw NoSuchElementException instead of returning undefined. HashSet and HashMap have no defined order, so they don't get these methods at all.

Sequenced.java
void main() {
    List<String> steps = new ArrayList<>(List.of("build", "test", "deploy"));
    IO.println(steps.getFirst() + " ... " + steps.getLast());
    steps.addFirst("checkout");
    IO.println(steps + ", reversed " + steps.reversed());

    var recent = new LinkedHashSet<>(List.of("a.txt", "b.txt", "c.txt"));
    recent.addFirst("c.txt");
    IO.println("set: " + recent + ", last " + recent.getLast());

    var tabs = new LinkedHashMap<String, Integer>();
    tabs.put("home", 1);
    tabs.put("shop", 2);
    tabs.putFirst("cart", 3);
    IO.println("map: " + tabs + ", first " + tabs.firstEntry() + ", last " + tabs.lastEntry());
    IO.println("polled " + tabs.pollLastEntry() + ", left " + tabs);

    var reversedView = steps.reversed();
    steps.add("monitor");
    IO.println("view sees the change: " + reversedView.getFirst());

    try {
        new ArrayList<String>().getFirst();
    } catch (NoSuchElementException e) {
        IO.println("empty list: NoSuchElementException");
    }
}
Terminal
$ java Sequenced.java
build ... deploy
[checkout, build, test, deploy], reversed [deploy, test, build, checkout]
set: [c.txt, a.txt, b.txt], last b.txt
map: {cart=3, home=1, shop=2}, first cart=3, last shop=2
polled shop=2, left {cart=3, home=1}
view sees the change: monitor
empty list: NoSuchElementException
What’s happening
  1. getFirst() and getLast() replace get(0) and get(size() - 1): build ... deploy. addFirst inserts at index 0.
  2. reversed() returns a reverse-ordered view, not a copy: printing it shows [deploy, test, build, checkout] without building a new list.
  3. On a LinkedHashSet, addFirst("c.txt") doesn't add a duplicate: the element already exists, so it's moved to the front. That makes "most recently used first" lists one call. getLast() is now b.txt, which before Java 21 needed a loop.
  4. On a LinkedHashMap, putFirst inserts cart at the front; firstEntry and lastEntry read the ends, and pollLastEntry removes and returns the last one (shop=2).
  5. Because reversedView is a view of steps, adding monitor to steps shows up as the view's first element.
  6. On an empty list, getFirst() throws NoSuchElementException. Check isEmpty() first when a collection can be empty.
AdvancedGotcha: immutable lists and reversed views

The new methods follow the collection's rules: on an immutable list, reading works and changing throws. And a reversed() view of a modifiable list writes through to it.

Views.java
void main() {
    List<Integer> fixed = List.of(1, 2, 3);
    IO.println("last of List.of: " + fixed.getLast() + ", reversed " + fixed.reversed());
    try {
        fixed.addFirst(0);
    } catch (UnsupportedOperationException e) {
        IO.println("addFirst on List.of: UnsupportedOperationException");
    }

    List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3));
    numbers.reversed().addFirst(4);
    IO.println("after reversed().addFirst(4): " + numbers);
}
Terminal
$ java Views.java
last of List.of: 3, reversed [3, 2, 1]
addFirst on List.of: UnsupportedOperationException
after reversed().addFirst(4): [1, 2, 3, 4]
What’s happening
  1. getLast() and reversed() work on List.of(…) because they only read.
  2. addFirst on it throws UnsupportedOperationException, like add.
  3. On a modifiable list, reversed().addFirst(4) adds to the front of the reversed view, which is the end of the original: [1, 2, 3, 4]. Views are powerful but can surprise; take a copy (new ArrayList<>(list.reversed())) when you want an independent list.

#Comparable and Comparator

Added

Sorting needs a rule for which of two objects comes first. Java has two places to put that rule. Comparable<T> is implemented by the class itself (compareTo) and defines its natural order: numbers by value, String alphabetically, LocalDate by date. Comparator<T> is a separate object that defines an ordering from outside, so a class can be sorted many ways: products by price, by name, by rating. Both return a negative number, zero or a positive number, exactly like the function you pass to JavaScript's sort((a, b) => …).

Since Java 8 you rarely write a comparator by hand. Comparator.comparing(keyExtractor) builds one from a method reference, and you chain it: .thenComparing(…) for tie-breakers, .reversed() to flip it, Comparator.reverseOrder() for one key in descending order, nullsFirst/nullsLast for missing values. List.sort is stable, as its documentation promises (equal elements keep their order), so chained sorts behave predictably. (JavaScript's Array.prototype.sort has been stable since ES2019, so that part is the same.)

The JavaScript trap that doesn't exist in Java: [10, 9, 1].sort() in JavaScript sorts as strings ([1, 10, 9]). Java sorts a List<Integer> numerically, because Integer's natural order is numeric.

Sorting.java
record Employee(String name, String dept, int salary) {}

void main() {
    var staff = new ArrayList<>(List.of(
            new Employee("maya", "eng", 120),
            new Employee("ana", "sales", 90),
            new Employee("rohit", "eng", 130),
            new Employee("li", "eng", 120),
            new Employee("sam", "sales", 95)));

    staff.sort(Comparator.comparing(Employee::dept)
            .thenComparing(Employee::salary, Comparator.reverseOrder())
            .thenComparing(Employee::name));
    staff.forEach(e -> IO.println(e.dept() + " " + e.salary() + " " + e.name()));

    var top = staff.stream().max(Comparator.comparingInt(Employee::salary)).orElseThrow();
    IO.println("highest paid: " + top.name());

    var numbers = new ArrayList<>(List.of(10, 9, 1));
    Collections.sort(numbers);
    IO.println("numbers: " + numbers);
}
Terminal
$ java Sorting.java
eng 130 rohit
eng 120 li
eng 120 maya
sales 95 sam
sales 90 ana
highest paid: rohit
numbers: [1, 9, 10]
What’s happening
  1. Comparator.comparing(Employee::dept) sorts by department first: eng before sales, alphabetically, using String's natural order.
  2. .thenComparing(Employee::salary, Comparator.reverseOrder()) breaks ties within a department by salary, highest first. In eng, rohit (130) comes before the two on 120.
  3. .thenComparing(Employee::name) breaks the remaining tie: li before maya, both on 120.
  4. max(Comparator.comparingInt(Employee::salary)) uses the same building blocks to find the top earner (comparingInt avoids boxing the int). max returns an Optional, and orElseThrow() unwraps it (chapter 05).
  5. Collections.sort on [10, 9, 1] uses Integer's natural order and gives [1, 9, 10], the numeric order JavaScript's default sort() wouldn't.
AdvancedImplementing Comparable, and the subtraction trap

A record can implement Comparable to give itself a natural order. The neat way is to delegate to a Comparator constant. The old way, return this.x - other.x;, has a bug: subtraction can overflow.

Versions.java
record Version(int major, int minor) implements Comparable<Version> {
    private static final Comparator<Version> ORDER =
            Comparator.comparingInt(Version::major).thenComparingInt(Version::minor);

    @Override
    public int compareTo(Version other) {
        return ORDER.compare(this, other);
    }
}

void main() {
    var versions = new ArrayList<>(List.of(new Version(2, 1), new Version(1, 10), new Version(2, 0)));
    Collections.sort(versions);
    IO.println(versions);

    var values = new ArrayList<>(List.of(Integer.MIN_VALUE, 1, -1));
    values.sort((a, b) -> a - b);
    IO.println("a - b:           " + values);
    values.sort(Integer::compare);
    IO.println("Integer.compare: " + values);
}
Terminal
$ java Versions.java
[Version[major=1, minor=10], Version[major=2, minor=0], Version[major=2, minor=1]]
a - b:           [-1, 1, -2147483648]
Integer.compare: [-2147483648, -1, 1]
What’s happening
  1. Version implements Comparable<Version>, so Collections.sort needs no comparator. compareTo delegates to ORDER: major first, then minor. Result: 1.10, 2.0, 2.1 (printed as records).
  2. The subtraction comparator looks fine but Integer.MIN_VALUE - 1 overflows to a large positive number, so the comparator claims MIN_VALUE is greater than 1. The sorted result comes out in the wrong order.
  3. Integer.compare(a, b) never overflows, and gives the right order: MIN_VALUE, -1, 1.
  4. Rule: never compare by subtracting. Use Integer.compare, Comparator.comparingInt, or compareTo on the field.
What does this print? (BigDecimal in a HashSet and a TreeSet)
Java
void main() {
    var a = new BigDecimal("1.0");
    var b = new BigDecimal("1.00");
    IO.println(a.equals(b) + " " + a.compareTo(b));
    IO.println(new HashSet<>(List.of(a, b)).size() + " " + new TreeSet<>(List.of(a, b)).size());
}
Show answer
Decimals.java
void main() {
    var a = new BigDecimal("1.0");
    var b = new BigDecimal("1.00");
    IO.println(a.equals(b) + " " + a.compareTo(b));
    IO.println(new HashSet<>(List.of(a, b)).size() + " " + new TreeSet<>(List.of(a, b)).size());
}
Terminal
$ java Decimals.java
false 0
2 1
What’s happening
  1. BigDecimal.equals compares the value and the scale (number of decimal places): 1.0 has scale 1, 1.00 has scale 2, so equals is false. compareTo compares only the numeric value: 0, equal.
  2. A HashSet uses hashCode and equals, so it keeps both: size 2.
  3. A TreeSet uses compareTo, which says they're the same, so the second is treated as a duplicate: size 1.
  4. BigDecimal's natural order is inconsistent with equals, and sorted collections follow the ordering, not equals. Prints false 0, then 2 1. (No import is needed: compact source files import all of java.base, which includes java.math.)

#Iterating and ConcurrentModificationException

Added

Most collection iterators are fail-fast: they remember the collection's modification count when they start, and if the collection is structurally changed (an element added or removed) by anything other than the iterator itself, the next step throws ConcurrentModificationException. The name misleads: it needs no threads. The usual cause is removing from a list inside a for-each loop over the same list, because for-each uses an iterator behind the scenes.

JavaScript does something quieter and worse: array.forEach while you splice the same array doesn't throw, it skips elements, and you get a wrong answer with no error. Java prefers to fail. The documentation is careful to say it's "best-effort" and should be used "only to detect bugs", so never rely on it being thrown (the quiz below shows a case where it isn't).

The fixes, best first: removeIf (Java 8) for "remove everything matching"; an explicit Iterator and its remove() when the logic is more involved; or build a new collection with a stream. For collections shared between threads, the concurrent collections iterate without throwing (chapter 09).

Cleanup.java
void main() {
    var cart = new ArrayList<>(List.of("keyboard", "SOLD OUT: mouse", "monitor", "SOLD OUT: cable"));

    try {
        for (String item : cart) {
            if (item.startsWith("SOLD OUT")) cart.remove(item);
        }
    } catch (ConcurrentModificationException e) {
        IO.println("for-each + remove: ConcurrentModificationException");
    }
    IO.println("after the failed loop: " + cart);

    cart = new ArrayList<>(List.of("keyboard", "SOLD OUT: mouse", "monitor", "SOLD OUT: cable"));
    for (Iterator<String> it = cart.iterator(); it.hasNext(); ) {
        if (it.next().startsWith("SOLD OUT")) it.remove();
    }
    IO.println("Iterator.remove: " + cart);

    cart = new ArrayList<>(List.of("keyboard", "SOLD OUT: mouse", "monitor", "SOLD OUT: cable"));
    cart.removeIf(item -> item.startsWith("SOLD OUT"));
    IO.println("removeIf: " + cart);
}
Terminal
$ java Cleanup.java
for-each + remove: ConcurrentModificationException
after the failed loop: [keyboard, monitor, SOLD OUT: cable]
Iterator.remove: [keyboard, monitor]
removeIf: [keyboard, monitor]
What’s happening
  1. The for-each loop asks a hidden iterator for each element. The second element starts with SOLD OUT, so cart.remove(item) removes it directly from the list, which increases the list's modification count.
  2. On the next step, the iterator sees the count no longer matches what it expected and throws ConcurrentModificationException.
  3. The list was still changed before the exception: SOLD OUT: mouse is gone, but SOLD OUT: cable isn't. A half-done cleanup is why this is worse than it looks if someone catches and ignores the exception.
  4. Iterator.remove() removes the element the iterator just returned and keeps the iterator's count in step, so the loop completes: [keyboard, monitor].
  5. removeIf does the same in one line and is the one to reach for. It's also faster on an ArrayList, which shifts the remaining elements once instead of once per removal.
AdvancedChanging a map while iterating

Maps have the same rule. Remove through a view's removeIf, and update values in place with replaceAll or Map.Entry.setValue, which aren't structural changes.

Stock.java
void main() {
    var stock = new TreeMap<>(Map.of("cable", 0, "keyboard", 5, "monitor", 2, "mouse", 0));

    stock.values().removeIf(count -> count == 0);
    IO.println("in stock: " + stock);

    for (var entry : stock.entrySet()) {
        entry.setValue(entry.getValue() * 2);
    }
    IO.println("doubled: " + stock);

    try {
        for (String name : stock.keySet()) {
            if (name.equals("keyboard")) stock.put("webcam", 1);
        }
    } catch (ConcurrentModificationException e) {
        IO.println("put while iterating: ConcurrentModificationException");
    }
}
Terminal
$ java Stock.java
in stock: {keyboard=5, monitor=2}
doubled: {keyboard=10, monitor=4}
put while iterating: ConcurrentModificationException
What’s happening
  1. values(), keySet() and entrySet() are live views of the map, so stock.values().removeIf(count -> count == 0) removes the matching entries from the map itself: cable and mouse go.
  2. entry.setValue changes a value without adding or removing a key, which isn't a structural modification, so the loop is allowed and the values double.
  3. put("webcam", 1) during iteration adds a key, a structural change: the next step of the key iterator throws ConcurrentModificationException.
  4. If you must add while looping, collect the additions in a separate list and putAll them after the loop.
What does this print? (removing the second-to-last element)
Java
void main() {
    var list = new ArrayList<>(List.of("a", "b", "c"));
    for (String s : list) {
        if (s.equals("b")) list.remove(s);
    }
    IO.println(list);
}
Show answer
Sneaky.java
void main() {
    var list = new ArrayList<>(List.of("a", "b", "c"));
    for (String s : list) {
        if (s.equals("b")) list.remove(s);
    }
    IO.println(list);
}
Terminal
$ java Sneaky.java
[a, c]
What’s happening
  1. Surprisingly, no exception. The iterator has returned a (cursor 1) and b (cursor 2) when b is removed, and the list's size drops from 3 to 2.
  2. The loop then calls hasNext(), which in ArrayList just checks cursor != size: 2 != 2 is false, so the loop ends without calling next(), which is where the modification check lives.
  3. So it prints [a, c] and c was never visited. Here that's harmless, but if the loop also did something with each element, c would have been silently skipped.
  4. This is why the documentation calls fail-fast behaviour "best-effort": a missing ConcurrentModificationException doesn't mean the code is right.

#Your turn: collections

Added
Your turn: word frequency, most common first

Count the words in "the cat and the hat and the bat" and print them most frequent first, ties in alphabetical order, as word=count pairs.

Show answer
Words.java
void main() {
    String text = "the cat and the hat and the bat";
    Map<String, Integer> counts = new HashMap<>();
    for (String word : text.split(" ")) {
        counts.merge(word, 1, Integer::sum);
    }

    List<Map.Entry<String, Integer>> entries = new ArrayList<>(counts.entrySet());
    entries.sort(Map.Entry.<String, Integer>comparingByValue().reversed()
            .thenComparing(Map.Entry.comparingByKey()));
    IO.println(entries);
}
Terminal
$ java Words.java
[the=3, and=2, bat=1, cat=1, hat=1]
What’s happening
  1. merge(word, 1, Integer::sum) counts each word: the=3, and=2, and 1 for each of cat, hat and bat.
  2. The entries go into an ArrayList so they can be sorted (a HashMap has no order to sort).
  3. Map.Entry.comparingByValue().reversed() puts the highest count first. The explicit <String, Integer> is needed: without it the line fails to compile ("no suitable method found for thenComparing"), because Java can't infer the entry types for a method call that's chained before the target type is known.
  4. thenComparing(Map.Entry.comparingByKey()) orders ties alphabetically: bat, cat, hat.
Your turn: the first non-repeated character

Write firstUnique(String s) that returns the first character that appears only once, so "swiss" gives w, and "aabb" gives none.

Show answer
Unique.java
Optional<Character> firstUnique(String s) {
    Map<Character, Integer> counts = new LinkedHashMap<>();
    for (char c : s.toCharArray()) {
        counts.merge(c, 1, Integer::sum);
    }
    for (var entry : counts.entrySet()) {
        if (entry.getValue() == 1) return Optional.of(entry.getKey());
    }
    return Optional.empty();
}

void main() {
    IO.println(firstUnique("swiss"));
    IO.println(firstUnique("aabb"));
    IO.println(firstUnique("java").map(String::valueOf).orElse("none"));
}
Terminal
$ java Unique.java
Optional[w]
Optional.empty
j
What’s happening
  1. A LinkedHashMap counts characters and remembers the order they first appeared: for swiss it holds s=3, w=1, i=1.
  2. The second loop walks that order and returns the first count of 1: w. A HashMap would also count correctly but could return i, because its order is by bucket.
  3. aabb has no unique character, so the method returns Optional.empty(), which prints as Optional.empty.
  4. For java, j is the first character that appears once (a appears twice), and map(String::valueOf).orElse("none") turns the Optional into plain text.
Your turn: fix the cleanup loop

This code should remove every negative reading but throws ConcurrentModificationException. Fix it two ways.

Java
var readings = new ArrayList<>(List.of(5, -1, 7, -3, 9));
for (Integer r : readings) {
    if (r < 0) readings.remove(r);
}
Show answer
Readings.java
void main() {
    var readings = new ArrayList<>(List.of(5, -1, 7, -3, 9));
    readings.removeIf(r -> r < 0);
    IO.println("removeIf: " + readings);

    var again = new ArrayList<>(List.of(5, -1, 7, -3, 9));
    var kept = again.stream().filter(r -> r >= 0).toList();
    IO.println("new list: " + kept + ", original untouched: " + again);
}
Terminal
$ java Readings.java
removeIf: [5, 7, 9]
new list: [5, 7, 9], original untouched: [5, -1, 7, -3, 9]
What’s happening
  1. The original loop removes -1 directly from the list while the for-each iterator is walking it, so the iterator's next step throws.
  2. removeIf(r -> r < 0) removes both negatives in one pass, safely: [5, 7, 9].
  3. The stream version doesn't modify anything: it builds a new (unmodifiable) list of the readings to keep, and the original stays [5, -1, 7, -3, 9]. Choose it when other code still needs the original.
  4. Note that in the original, readings.remove(r) with r an Integer calls remove(Object), so it did remove the value -1, not index -1: the bug was only the iteration.

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.