Java Collections interview questions and answers
Java Collections interview questions test whether you can pick the right List, Set, Map or Queue for a job, explain its cost, and avoid the contract traps that break code silently: equals and hashCode, comparators that disagree with equals, immutable views, and modifying a collection while you iterate it. Expect output-prediction snippets, a design question such as choosing a structure for a cache or leaderboard, and concurrency follow-ups at senior level.
By Evin JohnPublished 8 min read
Where collections questions come up
Almost every Java interview spends some time here, from campus placements to senior backend loops, because collections are the everyday tools of the language and their mistakes are easy to spot in code. Freshers get definitions and differences. Mid-level candidates get snippets that print something surprising and a question about which structure to use. Senior candidates get concurrency, memory and API-design angles. For the rest of the Java loop (JVM, Spring, concurrency in general), see Java developer interview questions.
- Rapid differencesArrayList versus LinkedList, HashSet versus TreeSet, HashMap versus Hashtable, Comparable versus Comparator.
- Predict the outputA dozen lines with a list of Integers, a TreeSet with a custom comparator or a stream collector, and you say what prints and why.
- Choose a structureAn LRU cache, a top-k leaderboard, deduplicating events in order, a work queue between threads.
- Concurrency follow-upWhat breaks when two threads share the structure, and which concurrent collection fixes it without a global lock.
Fundamentals: the framework and its interfaces
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is the Collections Framework? | Big picture | A set of interfaces (Collection, List, Set, Queue, Deque, Map), implementations and algorithms in java.util, so code can depend on an interface and swap the implementation. |
| Why is Map not a Collection? | Hierarchy | A map holds key and value pairs, not single elements, so it has its own interface. You get collection views of it through keySet, values and entrySet. |
| Collection versus Collections? | Naming | Collection is the root interface. Collections is a utility class with static helpers such as sort, unmodifiableList, synchronizedMap and emptyList. |
| List, Set or Map: how do you choose? | Modeling | List for ordered items with duplicates and index access, Set for uniqueness, Map for lookup by key. Then choose the implementation by ordering and cost needs. |
| HashSet, LinkedHashSet or TreeSet? | Ordering | HashSet has no order and constant-time operations on average. LinkedHashSet keeps insertion order. TreeSet keeps sorted order with logarithmic operations and supports range queries. |
| HashMap versus Hashtable? | Legacy | Hashtable is synchronized on every method and rejects null keys and values. HashMap is unsynchronized and allows one null key. Neither is the modern choice for shared state; use ConcurrentHashMap. |
| What does ArrayDeque replace? | Modern defaults | Stack (a synchronized Vector subclass) for LIFO use and usually LinkedList for queues. ArrayDeque is faster and does not accept nulls. |
| What is the default order of a PriorityQueue? | Heaps | Natural ordering, so the smallest element comes out first. Pass a comparator, for example Comparator.reverseOrder(), for a max-heap. |
| Why does iterating a PriorityQueue not print sorted order? | Heap internals | The iterator walks the backing array, which is only heap-ordered. Only repeated poll returns elements in priority order. |
| What is the difference between Iterator and ListIterator? | Iteration | ListIterator works on lists, moves both ways, reports indexes and can set or add during iteration. Iterator only moves forward and can remove. |
| Implementation | Get or lookup | Add | Remove | Notes |
|---|---|---|---|---|
| ArrayList | O(1) by index | Amortized O(1) at the end | O(n), elements shift | Backing array grows by about half its size when full. |
| LinkedList | O(n) by index | O(1) at either end | O(1) with an iterator in hand | Poor cache locality and a node object per element. |
| HashMap / HashSet | O(1) average | O(1) average | O(1) average | Degrades when hash codes collide; large bins become trees. |
| TreeMap / TreeSet | O(log n) | O(log n) | O(log n) | Red-black tree; floor, ceiling, headMap and tailMap for ranges. |
| PriorityQueue | O(1) peek | O(log n) offer | O(log n) poll, O(n) remove(Object) | Binary heap in an array. |
| ArrayDeque | O(1) at the ends | Amortized O(1) | O(1) at the ends | Circular array; no index access, no nulls. |
Intermediate: contracts and output traps
This is the section most candidates lose points on, because each trap compiles and runs without a warning. The program below was compiled and run on JDK 17; every comment shows the real output.
import java.util.*;
import java.util.stream.*;
public class Traps {
record Person(String name, int age) {}
public static void main(String[] args) {
List<Integer> ids = new ArrayList<>(List.of(10, 20, 30));
ids.remove(1); // removes index 1, not the value 1
ids.remove(Integer.valueOf(10)); // removes the value 10
System.out.println(ids); // [30]
List<String> fixed = Arrays.asList("a", "b");
try { fixed.add("c"); } catch (UnsupportedOperationException e) { System.out.println("asList is fixed-size"); }
try { List.of("a").contains(null); } catch (NullPointerException e) { System.out.println("List.of rejects null queries"); }
Set<Person> byName = new TreeSet<>(Comparator.comparing(Person::name));
byName.add(new Person("Ana", 30));
byName.add(new Person("Ana", 41)); // compares equal by name, silently dropped
System.out.println(byName.size()); // 1
Map<String, Integer> counts = new TreeMap<>();
for (String w : "to be or not to be".split(" ")) counts.merge(w, 1, Integer::sum);
System.out.println(counts); // {be=2, not=1, or=1, to=2}
try {
Stream.of("ant", "ape").collect(Collectors.toMap(s -> s.charAt(0), s -> s));
} catch (IllegalStateException e) { System.out.println("toMap: duplicate key"); }
PriorityQueue<Integer> heap = new PriorityQueue<>(List.of(5, 1, 4, 2));
System.out.print(heap.poll() + " " + heap.poll()); // 1 2
System.out.println();
}
}- Why did `ids.remove(1)` remove 20? Overload resolution prefers
remove(int index)over boxing toremove(Object). PassInteger.valueOf(1)to remove by value. - What can you do with the list from Arrays.asList? Read it and call set, which writes through to the array. Adding or removing throws, because the list is a fixed-size view of the array.
- How do List.of, Collections.unmodifiableList and List.copyOf differ? List.of builds a new immutable list and rejects nulls, even in contains. unmodifiableList is a read-only view, so changes to the original still show through. copyOf returns an immutable copy, or the same list if it is already immutable.
- Why did the TreeSet keep only one Ana? Sorted sets decide equality with compareTo or the comparator, not equals. When the comparator says zero, the second element is treated as a duplicate. Add tie-breakers with
thenComparing. - What does Map.merge save you? A get, a null check and a put.
merge(key, 1, Integer::sum)counts in one call, andcomputeIfAbsent(key, k -> new ArrayList<>()).add(v)groups in one. - Why does Collectors.toMap throw? Two elements produced the same key and no merge function was given. Pass one, such as
(a, b) -> a, and a map supplier if you need order. - What is wrong with using a mutable object as a HashMap key? If a field used by hashCode changes after insertion, the entry sits in the wrong bucket and lookups miss it, even with the same instance.
- What happens if equals is overridden and hashCode is not? Two equal objects get different hash codes, so a HashSet can hold both and a HashMap lookup with an equal key fails.
- Comparable or Comparator? Comparable defines one natural order inside the class. Comparators define as many external orders as you need and compose with comparing, thenComparing and reversed.
- Is Collections.sort stable? Yes for object lists: equal elements keep their relative order, so sorting by city and then stably by name gives a correct two-key result.
Iteration, views and modification
- When do you get ConcurrentModificationException in a single thread? When a collection is structurally changed during a for-each loop other than through the iterator. The iterator compares a modification counter and fails fast. Use
removeIforiterator.remove(). - Is fail-fast behavior guaranteed? No. It is a best-effort bug detector, not a thread-safety mechanism, and code must never rely on catching it.
- What does subList return? A view backed by the original list. Clearing it removes that range from the original, and structurally changing the original afterwards makes the view throw.
- What is a weakly consistent iterator? The kind ConcurrentHashMap and the concurrent queues return. It never throws ConcurrentModificationException and may or may not reflect changes made after it was created.
- How does CopyOnWriteArrayList iterate safely? Every write copies the array, and iterators read a snapshot. That suits listener lists with rare writes and frequent reads, and is a poor fit for write-heavy data.
- Does keySet return a copy? No, it is a live view. Removing a key from it removes the entry from the map, and adding to it is not supported.
- What changed with sequenced collections? Newer JDKs (Java 21 onward) add SequencedCollection, SequencedSet and SequencedMap, giving lists, deques, LinkedHashSet and sorted sets common getFirst, getLast and reversed methods. Mention it if the team is on a recent JDK.
Senior and scenario questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
Why is Collections.synchronizedMap not enough for check-then-put? | Atomicity | Each call is synchronized, but if (!map.containsKey(k)) map.put(k, v) is two calls with a gap. Use ConcurrentHashMap.putIfAbsent or computeIfAbsent, or lock around both. |
| How does ConcurrentHashMap avoid one big lock? | Concurrency | Reads do not block, and writes lock or use compare-and-swap at the level of a single bin, so threads touching different keys rarely wait for each other. |
| Why does ConcurrentHashMap reject null? | API design | In a concurrent map, get returning null could mean absent or mapped to null, and you cannot check again atomically. Banning null removes the ambiguity. |
| Which queue would you use between producer and consumer threads? | BlockingQueue | A bounded ArrayBlockingQueue or LinkedBlockingQueue with put and take, so a slow consumer applies back-pressure instead of letting memory grow. |
| How would you build an LRU cache? | Structure choice | LinkedHashMap in access order with removeEldestEntry for a single thread; for concurrency, a caching library or a ConcurrentHashMap plus a lock-protected order structure. |
| How do you keep the top 100 scores from a stream of millions? | Heaps | A min-heap of size 100: offer each score and poll when the size passes 100. That is O(n log k) time and O(k) memory. |
| A HashMap with millions of entries uses far too much memory. Why? | Footprint | Each entry is an object with a key, value, hash and next pointer, and boxed keys and values add more. Consider primitive collections, arrays, or a different representation. |
| Why set an initial capacity? | Resizing | If you know the size, sizing the map up front avoids repeated rehashing as it grows. Remember to divide the expected count by the load factor. |
| When is EnumMap or EnumSet the right choice? | Specialized types | When keys are enum constants: they are backed by arrays or bit vectors, so they are compact and fast, and iterate in declaration order. |
| What does WeakHashMap do, and is it a cache? | References | It holds keys weakly, so entries disappear after a key is no longer strongly referenced elsewhere. It suits metadata attached to objects, not a size-bounded cache. |
- Should a method return null or an empty collection? An empty collection. Callers can loop without a null check, and
List.of()orCollections.emptyList()cost nothing. - Should a public API return a mutable internal list? No. Return an unmodifiable copy or view, otherwise callers can change your object's state behind its back.
- Stream.toList or Collectors.toList?
Stream.toList()(Java 16 and later) returns an unmodifiable list.Collectors.toList()makes no promise about mutability, so code that later adds to it depends on an implementation detail. - How would you group orders by customer and sum the amounts?
groupingBy(Order::customerId, summingLong(Order::amountMinor)), with a TreeMap supplier if the output must be sorted.
Fictional example
- Interviewer
- Events arrive with an ID. Drop repeats, but downstream needs them in arrival order. What would you use?
- Candidate
- For a single thread, a LinkedHashSet of IDs gives constant-time membership checks and keeps insertion order, so I can add each event's ID and forward the event only when add returns true. I would make sure the ID type has proper equals and hashCode; a record does that for me. If the stream is unbounded I cannot keep every ID forever, so I would cap it, for example a LinkedHashMap with removeEldestEntry after a window that matches how late duplicates can arrive. If several threads consume, I would switch to ConcurrentHashMap's key set for the seen check and keep ordering per partition rather than globally.
Practice plan for Java Collections
- Day 1: draw the interface tree from memory and fill in the cost table above without looking.
- Day 2: type out the trap program, predict each line before running it, and explain every surprise aloud.
- Day 3: write a class with equals, hashCode and compareTo that disagree, then watch HashSet and TreeSet behave differently.
- Day 4: build an LRU cache with LinkedHashMap and a top-k tracker with PriorityQueue, with a JUnit test for each.
- Day 5: run a producer and consumer on a bounded BlockingQueue and explain what happens when the consumer slows down.
Collections connect to several neighboring topics: data structures interview questions covers the theory behind lists, heaps and hash tables, multithreading interview questions goes deeper on locks and thread pools, and JUnit interview questions shows how to pin collection behavior down in tests.
Output-prediction rounds are won by saying the rule before the answer. Natively, an AI interview assistant for Mac and Windows, transcribes a mock Java round on your machine, so afterwards you can check whether you explained overload resolution or comparator equality or only stated the output. In practice it can read a snippet from a screenshot and suggest an explanation, and with Pro or the free trial it draws on the résumé and job description you add. You can go back over the transcript and notes later.
Questions people ask
What Java Collections questions are asked in interviews?
Differences such as ArrayList versus LinkedList and HashSet versus TreeSet, Big O of common operations, equals and hashCode, Comparable versus Comparator, immutable lists, ConcurrentModificationException and ConcurrentHashMap.
Why does a TreeSet drop elements that are not equal?
Sorted sets decide duplicates with compareTo or the comparator, not equals. If the comparator returns zero for two different objects, the second is treated as a duplicate. Add tie-breakers with thenComparing.
What is the difference between List.of and Arrays.asList?
List.of returns an immutable list that rejects nulls. Arrays.asList returns a fixed-size view of an array: you can set elements, which writes through to the array, but not add or remove.
Is HashMap thread-safe?
No. For shared maps use ConcurrentHashMap and its atomic methods such as computeIfAbsent and merge, rather than a synchronized wrapper with separate check and put calls.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
