Tech Interview RoomStudy guides

Java 21

Java 21: Keep a "recently viewed" list and access first and last elements. Compare Java 8 lists, LinkedHashSet, LinkedHashMap and Sequenced Collections.

Intermediate · 2 min read · Lesson 1 of 8 in Java 21

Problem

Track the last N distinct products a user viewed, most recent first; re-viewing a product moves it to the front; show the newest and oldest. Java 21's Sequenced Collections (JEP 431) add one API for "first, last and reversed" across lists, deques, ordered sets and ordered maps.

Approach 1: ArrayList (Java 8, O(n) per view)

remove(Object) and add(0, x) shift elements: fine for N = 10, poor for large N.

java
import java.util.ArrayList;
import java.util.List;

class RecentList {
    private final List<String> items = new ArrayList<>();
    private final int max;
    RecentList(int max) { this.max = max; }

    void view(String sku) {
        items.remove(sku);                                    // O(n)
        items.add(0, sku);                                    // O(n) shift
        if (items.size() > max) items.remove(items.size() - 1);
    }
    String newest() { return items.isEmpty() ? null : items.get(0); }
    String oldest() { return items.isEmpty() ? null : items.get(items.size() - 1); }   // the size()-1 idiom
    List<String> all() { return items; }
}

Approach 2: LinkedHashSet in Java 8 (O(1) updates, awkward reads)

Re-adding moves nothing, so you must remove then add (it goes to the end). Getting the last element or iterating newest-first needs a full traversal or a copy.

java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;

class RecentSetJava8 {
    private final LinkedHashSet<String> items = new LinkedHashSet<>();
    private final int max;
    RecentSetJava8(int max) { this.max = max; }

    void view(String sku) {
        items.remove(sku);
        items.add(sku);                                        // newest at the END
        if (items.size() > max) { Iterator<String> it = items.iterator(); it.next(); it.remove(); }
    }
    String newest() { String last = null; for (String s : items) last = s; return last; }   // O(n)
    List<String> all() { List<String> l = new ArrayList<>(items); Collections.reverse(l); return l; }
}

Approach 3: LinkedHashMap with access order (classic LRU, Java 8)

removeEldestEntry evicts automatically; still no direct "last entry" accessor before Java 21.

java
import java.util.LinkedHashMap;
import java.util.Map;

class RecentLru extends LinkedHashMap<String, Boolean> {
    private final int max;
    RecentLru(int max) { super(16, 0.75f, true); this.max = max; }
    @Override protected boolean removeEldestEntry(Map.Entry<String, Boolean> eldest) { return size() > max; }
    void view(String sku) { put(sku, Boolean.TRUE); }       // put moves an existing key to the end
}

Approach 4: Sequenced Collections (Java 21)

  • SequencedCollection: addFirst, addLast, getFirst, getLast, removeFirst, removeLast, reversed() (a live view).
  • For LinkedHashSet, addFirst(e) moves an existing element to the front.
  • SequencedMap (LinkedHashMap, TreeMap): putFirst, putLast, firstEntry, lastEntry, pollFirstEntry, pollLastEntry, sequencedKeySet().
java
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedCollection;

class RecentSequenced {
    private final LinkedHashSet<String> items = new LinkedHashSet<>();
    private final int max;
    RecentSequenced(int max) { this.max = max; }

    void view(String sku) {
        items.addFirst(sku);                                 // inserts or MOVES to the front: O(1)
        if (items.size() > max) items.removeLast();          // O(1)
    }
    String newest() { return items.isEmpty() ? null : items.getFirst(); }
    String oldest() { return items.isEmpty() ? null : items.getLast(); }
    List<String> all() { return List.copyOf(items); }
    SequencedCollection<String> oldestFirst() { return items.reversed(); }   // live view, no copy
}

class SequencedDemo {
    public static void main(String[] args) {
        String[] views = {"tv", "phone", "laptop", "phone", "watch"};
        RecentList a = new RecentList(3); RecentSetJava8 b = new RecentSetJava8(3);
        RecentLru c = new RecentLru(3); RecentSequenced d = new RecentSequenced(3);
        for (String v : views) { a.view(v); b.view(v); c.view(v); d.view(v); }
        System.out.println(a.all() + " " + b.all() + " " + d.all());          // [watch, phone, laptop] x3
        System.out.println(c.sequencedKeySet().reversed());                  // [watch, phone, laptop]  (Java 21 SequencedMap view)
        System.out.println(d.newest() + " / " + d.oldest() + " / " + d.oldestFirst());   // watch / laptop / [laptop, phone, watch]

        // The same API on other types
        List<Integer> list = new java.util.ArrayList<>(List.of(1, 2, 3));
        System.out.println(list.getFirst() + " " + list.getLast() + " " + list.reversed());   // 1 3 [3, 2, 1]
        LinkedHashMap<String, Integer> scores = new LinkedHashMap<>();
        scores.put("b", 2); scores.putFirst("a", 1); scores.putLast("c", 3);
        System.out.println(scores.firstEntry() + " " + scores.lastEntry() + " " + scores.pollFirstEntry() + " " + scores);   // a=1 c=3 a=1 {b=2, c=3}
    }
}

Feasible → optimal

  1. ArrayList: O(n) per view, simplest.
  2. LinkedHashSet/LinkedHashMap in Java 8: O(1) updates, but reading the newest element or reversing is O(n) or needs copies.
  3. Java 21 sequenced LinkedHashSet: O(1) for every operation, including getFirst, getLast and the reversed view: optimal, and the most readable. For a concurrent, size-bounded cache shared across threads, use Caffeine instead.

Follow-up questions interviewers ask

Try answering each one before you open it.

Which existing types became sequenced, and what does reversed() return?

List, Deque, LinkedHashSet, SortedSet/NavigableSet (TreeSet) are SequencedCollections (with SequencedSet for the sets); LinkedHashMap and SortedMap/NavigableMap (TreeMap) are SequencedMaps. HashSet and HashMap are not, because they have no defined order. reversed() returns a live view in reverse order, so changes through either view are visible in the other; no copy is made.

Why does `addFirst` throw on a TreeSet?

A sorted collection's order is determined by its comparator, so you cannot place an element at an arbitrary position: addFirst/addLast (and putFirst/putLast on TreeMap) throw UnsupportedOperationException. Reading operations like getFirst() and reversed() work normally.