Part 09 / Topic 5 of 10
Choosing the right collection
Stage 1 Part 4 used ArrayList, HashMap and HashSet as ready-made tools. Now that you know what the type parameter in List<String> means, the next question is which implementation of List/Set/Map/Deque actually fits the job — they are interfaces, and each one has more than one implementing class, with real trade-offs.
List: ArrayList vs. LinkedList
Both keep order and allow duplicates. ArrayList stores elements in one resizable array: reading get(i) is instant, but inserting in the middle shifts everything after it. LinkedList stores elements as linked nodes: adding/removing at either end is instant, but get(i) has to walk the list from the start. For almost all everyday code — iterating, reading by index, appending — reach for ArrayList first; LinkedList earns its place only when you are repeatedly adding/removing at the front or back (and even then, ArrayDeque below usually wins).
Set: HashSet vs. LinkedHashSet vs. TreeSet
All three forbid duplicates (decided by equals/hashCode, Part 8). They differ only in what order you get back when you iterate:
| Implementation | Order you get back | Typical use |
|---|---|---|
HashSet |
Not defined — do not rely on it | Fastest; use when you only care "is it in there?" |
LinkedHashSet |
The order items were first inserted | Dedupe a list while keeping first-seen order |
TreeSet |
Always sorted (natural order, or a Comparator) |
You need the unique items sorted, every time |
Set<String> hashSet = new HashSet<>(visitedCities);
Set<String> linkedHashSet = new LinkedHashSet<>(visitedCities);
Set<String> treeSet = new TreeSet<>(visitedCities);
HashSet (fastest, order not defined): size=4
LinkedHashSet (keeps first-seen order): [Pune, Delhi, Chennai, Mumbai]
TreeSet (always sorted): [Chennai, Delhi, Mumbai, Pune]
Map: HashMap vs. LinkedHashMap vs. TreeMap
The same three-way choice, but for keys instead of elements:
HashMap (fastest, order not defined): size=4
LinkedHashMap (insertion order kept): {Pune=2, Delhi=2, Chennai=1, Mumbai=1}
TreeMap (sorted by key): {Chennai=1, Delhi=2, Mumbai=1, Pune=2}
map.merge(key, 1, Integer::sum) is the idiomatic "add one, or start at one if the key is new" — it replaces a longer containsKey/get/put block.
Deque: one interface, two uses
Deque (double-ended queue, pronounced "deck") can act as either a stack or a queue — ArrayDeque is the idiomatic choice for both, faster than the old Stack and LinkedList classes for this job.
Deque<String> stack = new ArrayDeque<>();
stack.push("Pune"); stack.push("Delhi"); stack.push("Chennai");
stack.pop(); // Chennai -- LIFO: Last In, First Out
Deque<String> queue = new ArrayDeque<>();
queue.offer("Pune"); queue.offer("Delhi"); queue.offer("Chennai");
queue.poll(); // Pune -- FIFO: First In, First Out
stack (LIFO), pop(): Chennai, remaining: [Delhi, Pune]
queue (FIFO), poll(): Pune, remaining: [Delhi, Chennai]
Same object type, two different method pairs (push/pop for a stack, offer/poll for a queue) — pick the pair that matches what you are modelling, the underlying ArrayDeque does not care.
Java 21: sequenced collections
Before Java 21, getting the first and last element of a List or LinkedHashMap used different, inconsistent methods (or none at all for some types). Java 21's sequenced collections (JEP 431) give List, Deque, LinkedHashSet and LinkedHashMap one shared API: getFirst(), getLast(), and reversed() (a reversed view, not a copy).
List<String> itinerary = List.of("Pune", "Delhi", "Chennai");
System.out.println(itinerary.getFirst() + " " + itinerary.getLast()); // Pune Chennai
System.out.println(itinerary.reversed()); // [Chennai, Delhi, Pune]
getFirst: Pune, getLast: Chennai
reversed: [Chennai, Delhi, Pune]
firstEntry: Pune=1, lastEntry: Chennai=3
One more reminder from Stage 1: List.of(...) returns an unmodifiable list. Calling .add(...) on it compiles fine but throws at run time:
List.of(...).add(...) -> UnsupportedOperationException
Full program: examples/CollectionChoices.java.
Done here? The practice set for Part 9 — including the solutions — is on the part page.