Collections framework
Pick the right List, Set, Map or Queue and know their costs.
By Invicly Tech, , in Backend Java Development. About 12 minutes to read.
In short
The collections framework gives ready-made lists, sets, maps and queues. Choosing the right one is mostly about access pattern, ordering and the Big-O cost of the operations you use most.
Explained simply
A collection is an object that holds a group of other objects. Instead of writing your own resizable arrays or lookup tables, you use ready-made ones from java.util. They are well tested and fast, so the main skill is picking the right one.
There are four big families. A List keeps items in order and allows duplicates, like a shopping list. A Set refuses duplicates, like a guest list. A Map stores pairs of key and value, like a phone book. A Queue hands items out in a certain order, like a line at a counter.
Each family has several implementations. They behave the same from the outside but are built differently inside, so some operations are fast in one and slow in another. Big-O notation describes this: O(1) means the time stays the same as the collection grows, O(n) means it grows with the size.
In daily backend work, ArrayList and HashMap cover most needs. You reach for others when you need sorting (TreeMap), stable order (LinkedHashMap), a stack or queue (ArrayDeque), or always taking the smallest item first (PriorityQueue).
Press Play on a diagram to walk through it one step at a time.
- List (ordered, duplicates)
- ArrayList
- LinkedList
- Set (no duplicates)
- HashSet
- LinkedHashSet
- TreeSet (sorted)
- Queue / Deque
- ArrayDeque
- PriorityQueue
- LinkedList
- Map (key to value)
- HashMap
- LinkedHashMap
- TreeMap (sorted)
- get(i) is O(1)
- add at end is amortised O(1)
- Insert or remove in middle is O(n)
- Compact, cache-friendly memory
- get(i) is O(n)
- Add or remove at ends is O(1)
- Extra memory per node
- Rarely faster in practice
- get and put O(1) average
- No predictable order
- Allows one null key
- The default choice
- get and put O(1) average
- Insertion or access order
- Slightly more memory
- Good for LRU caches
- get and put O(log n)
- Keys always sorted
- floorKey, ceilingKey, subMap
- No null keys with natural order
- 1Look up by key?
Yes: a Map (HashMap by default)
- 2Must be unique?
Yes: a Set (HashSet by default)
- 3Need sorted order?
Yes: TreeMap or TreeSet
- 4Process in order?
FIFO or LIFO: ArrayDeque. Smallest first: PriorityQueue
- 5Otherwise
ArrayList
In depth
Inside HashMap
A HashMap is an array of buckets. To store a key, it calls key.hashCode(), mixes the bits, and uses the result to choose a bucket. If two keys land in the same bucket (a collision), they are kept together, and equals() tells them apart on lookup. With a good hashCode, most buckets hold zero or one entry, so get and put are O(1) on average.
The table starts with 16 buckets. When the number of entries passes 75 percent of the bucket count (the load factor 0.75), the table doubles and every entry is moved. If you know you will store a million items, size it upfront to avoid repeated resizing. If one bucket grows past 8 entries and the table has at least 64 buckets, that bucket turns into a balanced tree, so even bad hash codes give O(log n) instead of O(n).
- 1key.hashCode()
An int computed from the key
- 2Choose bucket
Hash bits pick an index in the array
- 3Search bucket
equals() finds an existing key
- 4Replace or append
Old value replaced, or new entry added
- 5Resize if needed
Over 75% full: double the table
How ArrayList grows
An ArrayList wraps a plain array. new ArrayList<>() starts with an empty array and allocates room for 10 elements on the first add. When the array is full, it allocates a new one about 1.5 times bigger and copies everything over. Each single copy costs O(n), but it happens so rarely that adding at the end is O(1) on average, which is what amortised O(1) means.
Inserting or removing in the middle shifts every element after that position, which is O(n). That sounds bad, but the shift is one fast memory copy, so for small and medium lists ArrayList still beats LinkedList, whose nodes are spread across memory. If you know the final size, pass it to the constructor: new ArrayList<>(10_000).
- get(i) and set(i) are O(1)
- add at end: amortised O(1)
- add or remove at index i: O(n)
- contains and indexOf: O(n) linear scan
Sorted collections and their navigation methods
TreeMap and TreeSet keep keys sorted using a red-black tree, a self-balancing binary tree. Every get, put and remove is O(log n). The order comes from the key's compareTo (Comparable) or from a Comparator you pass to the constructor.
Their real power is navigation. floorKey(x) finds the largest key less than or equal to x, ceilingKey(x) the smallest key greater than or equal to x, and headMap, tailMap and subMap give live views of a range. This is perfect for price tiers, time windows or finding the nearest slot. One trap: a TreeSet decides equality with compareTo, not equals. If your comparator says two different objects compare as 0, the set keeps only one of them.
- firstKey() and lastKey() give the extremes
- pollFirstEntry() removes and returns the smallest
- descendingMap() iterates largest first
Queues, deques and priority queues
Deque (pronounced deck) lets you add and remove at both ends. ArrayDeque is the go-to implementation: use push and pop for a stack (last in, first out), and offer and poll for a queue (first in, first out). It is faster than the old Stack class and than LinkedList. It does not accept null.
PriorityQueue is a binary heap. offer and poll are O(log n), peek is O(1), and poll always returns the smallest element by natural order or by your Comparator. For largest first, pass Comparator.reverseOrder(). Iterating over a PriorityQueue or printing it does not show sorted order; only repeated poll calls do. In concurrent code, use the BlockingQueue family (ArrayBlockingQueue, LinkedBlockingQueue) instead.
Immutable, unmodifiable and sequenced collections
List.of, Set.of and Map.of (Java 9) create truly immutable collections. Any add or remove throws UnsupportedOperationException, and they reject null elements. List.copyOf makes an immutable copy of an existing list. Collections.unmodifiableList is different: it is a read-only view, so changes to the original list still show through.
Java 21 added sequenced collections. List, Deque, LinkedHashSet, LinkedHashMap, TreeSet and TreeMap now share methods like getFirst(), getLast(), addFirst(), removeLast() and reversed(). So list.getLast() replaces list.get(list.size() - 1). Also remember: removing items in a for-each loop throws ConcurrentModificationException. Use list.removeIf(x -> ...) or an explicit Iterator with it.remove().
- Map.of allows up to 10 pairs; use Map.ofEntries for more
- Set.of throws if you pass duplicates
- Return immutable collections from methods to protect internal state
Learn it in 5 short steps
About 1h 10m each. Track them with a timer in your plan.
- 1Compare ArrayList and LinkedList~1h 10m
- 2Use HashSet, TreeSet and LinkedHashSet~1h 10m
- 3Use HashMap, TreeMap and LinkedHashMap~1h 10m
- 4Work with Queue, Deque and PriorityQueue~1h 10m
- 5Learn Big-O costs of common operations~1h 10m
Key points
- HashMap and HashSet give average O(1) lookups but no ordering.
- TreeMap and TreeSet keep keys sorted with O(log n) operations.
- LinkedHashMap keeps insertion order, handy for predictable output and LRU caches.
- Use ArrayDeque for stacks and queues and PriorityQueue when you need the smallest first.
Key terms
Tap a card to flip it. 0/5 known
Examples
List<String> words = List.of("to", "be", "or", "not", "to", "be");
Map<String, Integer> counts = new HashMap<>();
for (String w : words) counts.merge(w, 1, Integer::sum);
Set<String> sorted = new TreeSet<>(words); // [be, not, or, to]
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); stack.push(2);
int top = stack.pop(); // 2
PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(5, 1, 3));
int smallest = pq.poll(); // 1A tiny LRU cache with LinkedHashMap
You need to keep the 100 most recently used results and drop the oldest. Step 1: create a LinkedHashMap with accessOrder set to true, so every get moves the entry to the end. Step 2: override removeEldestEntry, which LinkedHashMap calls after each put. Step 3: return true when the size passes the limit, and the least recently used entry at the front is removed. Note: this class is not thread-safe; for production caches use a library such as Caffeine.
class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int max;
LruCache(int max) {
super(16, 0.75f, true); // true = access order
this.max = max;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > max;
}
}
// var c = new LruCache<String, Integer>(2);
// c.put("a", 1); c.put("b", 2); c.get("a"); c.put("c", 3); // "b" is evictedTop 3 scores from a big stream with a PriorityQueue
You read a million scores and need only the three highest. Sorting everything costs O(n log n). Instead, step 1: keep a min-heap of size 3. Step 2: add each score. Step 3: if the heap grows past 3, poll removes the smallest, so only the best three stay. The work is O(n log k) with k = 3, and memory stays tiny. Step 4: at the end, the heap holds the top three; sort them for display.
static List<Integer> top3(int[] scores) {
PriorityQueue<Integer> heap = new PriorityQueue<>(); // smallest on top
for (int s : scores) {
heap.offer(s);
if (heap.size() > 3) heap.poll(); // drop the smallest
}
List<Integer> result = new ArrayList<>(heap);
result.sort(Comparator.reverseOrder());
return result;
}
// top3(new int[]{40, 95, 12, 77, 88, 63}) -> [95, 88, 77]Quick reference
- HashMap starts with 16 buckets and doubles when 75% full
- new HashMap<>(expected * 4 / 3 + 1) avoids resizes for a known size
- TreeMap: floorKey, ceilingKey, subMap for range lookups in O(log n)
- Use ArrayDeque for stacks and queues, not Stack or LinkedList
- PriorityQueue: offer and poll O(log n), peek O(1), printing is not sorted
- List.of is immutable and rejects null; unmodifiableList is only a view
- Remove while iterating with list.removeIf(...) or Iterator.remove()
- Java 21: list.getFirst(), list.getLast(), list.reversed()
Common mistakes
- Using LinkedList.get(i) in a loop, which makes the loop O(n squared).
- Mutating a HashMap key after insertion, so it can no longer be found.
- Removing items in a for-each loop, which throws ConcurrentModificationException.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Given a list of words, print each distinct word once, in the order it first appeared.
- Exercise 2medium
Check whether a string of brackets like "{[()]}" is balanced, using a Deque as a stack.
- Exercise 3hard
Shipping costs depend on weight tiers: from 0 kg costs 5, from 2 kg costs 9, from 10 kg costs 20. Write cost(double kg) using a TreeMap so new tiers need only one new line.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is LinkedList ever the right choice?
- Rarely. ArrayDeque is better for queues and stacks, and ArrayList is better for indexed lists. LinkedList only helps when you insert or remove in the middle through an iterator you already hold, and even then memory overhead often eats the gain.
- What is the difference between HashMap and Hashtable?
- Hashtable is a legacy class with every method synchronized and no null keys or values. Use HashMap in single-threaded code and ConcurrentHashMap when threads share the map.
- Why does my HashMap lookup return null for a key I just put?
- Usually the key class does not override equals and hashCode consistently, or a field used in hashCode changed after the key was inserted. Use immutable keys such as String, records or enums.
- Does HashMap keep insertion order?
- No. The order depends on hash codes and can change after a resize. Use LinkedHashMap when you need insertion order.