Java Collections
The Framework at a Glance
The framework lives in java.util. Its interfaces define behavior; several classes implement each interface with different performance trade-offs. Code should declare variables with the interface and choose the implementation only where the object is created.
Core Interfaces
| Interface | Contains | Typical implementations |
|---|---|---|
List | Ordered elements, duplicates allowed, access by index | ArrayList, LinkedList |
Set | Unique elements | HashSet, LinkedHashSet, TreeSet |
Queue / Deque | Elements processed from the ends | ArrayDeque, PriorityQueue |
Map | Key–value pairs, unique keys (not a Collection) | HashMap, LinkedHashMap, TreeMap |
Choosing an Implementation
| Class | Order | Strength | Cost |
|---|---|---|---|
ArrayList | insertion | Fast index access and iteration; the default list | Inserting or removing in the middle shifts elements |
LinkedList | insertion | Cheap insert/remove at a known position via an iterator | Slow index access; more memory; rarely the best choice |
HashSet / HashMap | none | Constant-time add, remove and lookup on average | Needs correct equals and hashCode |
LinkedHashSet / LinkedHashMap | insertion | Hash speed with predictable iteration | A little more memory |
TreeSet / TreeMap | sorted | Sorted iteration, ranges, nearest-key queries | Logarithmic operations; elements must be comparable |
ArrayDeque | insertion | Fast stack and queue at both ends | No null elements, no index access |
PriorityQueue | by priority | Always removes the smallest (or highest-priority) element | Iteration order is not sorted |
The complexity behind these trade-offs is explained in the DSA lessons on arrays, hash tables and trees.
Lists, Sets and Maps in Use
// The three core interfaces: List (ordered), Set (unique), Map (key to value).
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
class CollectionsTour {
public static void main(String[] args) {
List<String> cart = new ArrayList<>(List.of("tea", "milk", "tea", "bread"));
cart.add(1, "honey"); // insert by position
cart.removeIf(item -> item.equals("milk")); // remove by condition
System.out.println("list: " + cart + ", second = " + cart.get(1));
Set<String> unique = new LinkedHashSet<>(cart); // duplicates dropped, insertion order kept
Set<String> sorted = new TreeSet<>(cart); // duplicates dropped, natural order
System.out.println("linked set: " + unique + ", tree set: " + sorted);
Map<String, Double> prices = new HashMap<>();
prices.put("tea", 4.5);
prices.put("bread", 2.0);
prices.putIfAbsent("tea", 9.9); // ignored: key already present
System.out.println("tea = " + prices.get("tea")
+ ", coffee = " + prices.getOrDefault("coffee", 0.0));
List<String> fixed = List.of("a", "b"); // immutable
try {
fixed.add("c");
} catch (UnsupportedOperationException e) {
System.out.println("List.of is immutable");
}
}
}
Output:
list: [tea, honey, tea, bread], second = honey
linked set: [tea, honey, bread], tree set: [bread, honey, tea]
tea = 4.5, coffee = 0.0
List.of is immutable
Immutable Collections
The factories List.of, Set.of and Map.of (Java 9+) create compact, unmodifiable collections; any attempt to change them throws UnsupportedOperationException, and they reject null elements. List.copyOf makes an unmodifiable copy of an existing collection. Return immutable collections from methods whenever callers should not change them; it removes a whole class of bugs.
Working with Maps
Modern Map methods replace most hand-written “check, then put” code: getOrDefault, putIfAbsent, computeIfAbsent (ideal for maps of lists) and merge (ideal for counters). A TreeMap keeps its keys sorted, which makes the word count below print in alphabetical order.
// Count words with Map.merge, then report them sorted by count.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
class WordFrequency {
public static void main(String[] args) {
String text = "the cat and the hat and the bat";
Map<String, Integer> counts = new TreeMap<>(); // keys kept in alphabetical order
for (String word : text.split(" ")) {
counts.merge(word, 1, Integer::sum); // insert 1, or add 1 to the existing count
}
System.out.println(counts);
List<Map.Entry<String, Integer>> byCount = new ArrayList<>(counts.entrySet());
byCount.sort(Map.Entry.<String, Integer>comparingByValue().reversed());
System.out.println("most frequent: " + byCount.get(0).getKey());
}
}
Output:
{and=2, bat=1, cat=1, hat=1, the=3}
most frequent: the
Queues, Stacks and Sequences
Stacks, Queues and Priorities
ArrayDeque is the recommended stack and queue — prefer it to the legacy Stack and Vector classes, which synchronize every call. A PriorityQueue always hands out its smallest element first, according to natural order or a Comparator.
Sequenced Collections
Java 21 added sequenced collections: List, Deque, LinkedHashSet and LinkedHashMap now share getFirst, getLast, addFirst, addLast and reversed.
// Deque as stack and queue, PriorityQueue, and Java 21 sequenced collections.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
class QueuesAndSequences {
public static void main(String[] args) {
Deque<String> stack = new ArrayDeque<>();
stack.push("a"); stack.push("b"); stack.push("c");
System.out.println("stack pop: " + stack.pop()); // c: last in, first out
Queue<String> queue = new ArrayDeque<>(List.of("first", "second"));
queue.offer("third");
System.out.println("queue poll: " + queue.poll()); // first: first in, first out
Queue<Integer> tasks = new PriorityQueue<>(List.of(5, 1, 4, 2));
StringBuilder order = new StringBuilder();
while (!tasks.isEmpty()) order.append(tasks.poll()).append(' ');
System.out.println("priority order: " + order.toString().trim());
List<String> steps = new ArrayList<>(List.of("wake", "code", "sleep"));
System.out.println(steps.getFirst() + " .. " + steps.getLast()); // Java 21
System.out.println("reversed view: " + steps.reversed());
}
}
Output:
stack pop: c
queue poll: first
priority order: 1 2 4 5
wake .. sleep
reversed view: [sleep, code, wake]
Common Pitfalls
Mistakes to Avoid
- Modifying while iterating: calling
list.removeinside a for-each loop throwsConcurrentModificationException. UseremoveIfor an explicitIterator. - Mutable keys: changing a field that
hashCodedepends on after inserting the object into aHashSetorHashMapmakes it unfindable. Arrays.asListreturns a fixed-size view of the array:setworks,addandremovethrow.- Thread safety: the standard implementations are not synchronized. Use
java.util.concurrentclasses such asConcurrentHashMapwhen several threads share a collection.
Practice
Exercises
- Build a
Map<String, List<String>>that groups words by their first letter, usingcomputeIfAbsent. - Use a
TreeMap'sfloorKeyto find the tax band for an income from a map of band thresholds. - Simulate a print queue where urgent jobs go first, using a
PriorityQueuewith aComparator. The runnable lab demos 37 to 42 show more collection programs.