Collections framework: choosing the right one
## Start with the requirement, not the class
- Need position/order and duplicates? Use a
List. Example: cart lines, exam answers, playlist tracks. Start withArrayList. - Need uniqueness? Use a
Set. Example: prevent a user from enrolling in the same course twice, or collect distinct tags. PickHashSetunless order matters. - Need lookup by a key? Use a
Map. Example: course code → course, user ID → profile, SKU → stock quantity. PickHashMapfor ordinary lookup. - Need items processed in arrival order? Use a
Queue. Example: email jobs waiting to send. FIFO means first submitted, first processed. - Need both ends? Use a
Deque. Example: undo/redo, recent navigation, sliding-window algorithms. - Need highest priority first? Use
PriorityQueue. Example: urgent support tickets before normal tickets.
The core interfaces:
List: ordered, allows duplicates. Default choice:ArrayList.LinkedListis rarely better.Set: no duplicates.HashSet(fast, no order),LinkedHashSet(insertion order),TreeSet(sorted).Map: key to value.HashMap,LinkedHashMap,TreeMap, andConcurrentHashMapwhen several threads share it.QueueandDeque:ArrayDequefor stacks and queues,PriorityQueuefor "smallest first".
Java 9 added immutable factories: List.of, Set.of and Map.of. Java 21 added sequenced collections: getFirst(), getLast() and reversed() on lists, deques and ordered sets and maps.
## A realistic JavaAtlas course catalog example
A catalog needs different answers: show courses in display order, avoid duplicate tags, fetch a course by slug, and count page views. These are four different collection jobs—not one collection for everything.
The collections hierarchy
Think of Java Collections as a toolbox—not one giant container. A List is your ordered shopping list, a Set is a guest list that rejects duplicate names, a Queue is a line at a ticket counter, and a Map is a phone book (name → number).
The family tree is Iterable → Collection → List, Set and Queue/Deque. Map is separate because it stores key-value pairs. The trick: code to the interface (List<String> names = new ArrayList<>()) so you can swap the tool without rewriting your application.
List, Set, Queue and Map at a glance
Imagine building an online store: keep cart items in a List, prevent duplicate coupon codes with a Set, process checkout jobs in a Queue, and find a customer by ID with a Map.
- List: ordered, allows duplicates, access by index (
ArrayList,LinkedList). - Set: no duplicates (
HashSet,LinkedHashSet,TreeSet). - Queue/Deque: process in order, FIFO or LIFO (
ArrayDeque,PriorityQueue). - Map: keys to values, unique keys (
HashMap,LinkedHashMap,TreeMap).
Quick challenge: Which structure would you use to remember every unique visitor to a website? Answer: a Set—and usually a HashSet for fast membership checks.
Choosing the right collection
- Need order and index access →
ArrayList - Need to check "seen before?" quickly →
HashSet - Need unique items in insertion order →
LinkedHashSet - Need sorted items or range queries →
TreeSet/TreeMap - Need a stack or queue →
ArrayDeque - Need "smallest next" →
PriorityQueue - Need lookups by key →
HashMap - Shared between threads →
ConcurrentHashMap,CopyOnWriteArrayList
Iterators and fail-fast behaviour
An Iterator walks a collection with hasNext and next, and can remove the current element safely. Changing the collection any other way during iteration throws ConcurrentModificationException (fail-fast). removeIf is the simplest safe removal.
Iterator<Order> it = orders.iterator();
while (it.hasNext()) {
if (it.next().isCancelled()) it.remove(); // safe
}
orders.removeIf(Order::isCancelled); // simplerImmutable and unmodifiable collections
List.of, Set.of and Map.of (Java 9) create unmodifiable collections that reject null. List.copyOf makes an unmodifiable copy. Collections.unmodifiableList is only a read-only view: changes to the original still show through.
List<String> fixed = List.of("a", "b");
// fixed.add("c"); // UnsupportedOperationException
List<String> copy = List.copyOf(mutable); // independent snapshotThe Collections utility class
java.util.Collections has handy static methods: sort, reverse, shuffle, max, min, frequency, nCopies, emptyList, swap and synchronizedList.
Collections.sort(names);
Collections.reverse(names);
int twos = Collections.frequency(List.of(2, 3, 2), 2); // 2
List<String> blanks = Collections.nCopies(3, "");Sequenced collections (Java 21)
Lists, deques, LinkedHashSet, TreeSet, LinkedHashMap and TreeMap now share getFirst(), getLast(), addFirst(), removeLast() and reversed(), instead of each having its own way.
List<String> steps = new ArrayList<>(List.of("plan", "build", "ship"));
steps.getFirst(); // "plan"
steps.getLast(); // "ship"
steps.reversed(); // [ship, build, plan] (a view)Making your own class iterable
Implement Iterable<T> (one method, iterator()) and your class works in for-each loops. The iterator keeps track of where it is with hasNext() and next().
record Range(int from, int to) implements Iterable<Integer> {
@Override public Iterator<Integer> iterator() {
return new Iterator<>() {
private int next = from;
@Override public boolean hasNext() { return next < to; }
@Override public Integer next() {
if (!hasNext()) throw new NoSuchElementException();
return next++;
}
};
}
}
for (int i : new Range(1, 4)) System.out.print(i + " "); // 1 2 3Example
// 1) List: preserve display order; duplicates can be meaningful (two cart lines)
List<String> featuredCourses = new ArrayList<>(List.of("Java", "Spring Boot", "Java"));
featuredCourses.add("Microservices");
System.out.println(featuredCourses.get(0)); // Java: index-based access
// 2) Set: collect unique tags (order is not important here)
Set<String> tags = new HashSet<>(List.of("java", "backend", "java"));
System.out.println(tags.size()); // 2
// 3) Map: direct lookup by a stable key
Map<String, String> courseBySlug = new HashMap<>();
courseBySlug.put("spring-boot", "Spring Boot in Practice");
String title = courseBySlug.get("spring-boot");
// 4) Map counting: page views per course
Map<String, Integer> views = new HashMap<>();
views.merge("spring-boot", 1, Integer::sum); // first view -> 1
views.merge("spring-boot", 1, Integer::sum); // next view -> 2
// 5) Queue: jobs wait in submission order
Queue<String> emails = new ArrayDeque<>();
emails.offer("welcome-email");
emails.offer("receipt-email");
String nextEmail = emails.poll(); // welcome-email
// 6) Deque: newest navigation page is at the front
Deque<String> browserHistory = new ArrayDeque<>();
browserHistory.push("/home");
browserHistory.push("/courses");
browserHistory.pop(); // back to /home
// 7) PriorityQueue: highest priority job first
record SupportTicket(String id, int priority) {}
PriorityQueue<SupportTicket> tickets = new PriorityQueue<>(
Comparator.comparingInt(SupportTicket::priority).reversed());
tickets.offer(new SupportTicket("normal", 1));
tickets.offer(new SupportTicket("urgent", 10));
SupportTicket first = tickets.poll(); // urgent
topics.add("Kafka");
Collections.sort(topics); // [JPA, Java, Kafka, Spring]
Set<String> tags = new TreeSet<>(Set.of("jvm", "api", "orm")); // sorted
Map<String, Integer> views = new HashMap<>();
views.merge("streams", 1, Integer::sum); // count occurrences
int records = views.getOrDefault("records", 0);
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.pop(); // 2
System.out.println(topics.getFirst()); // Java 21+: JPA
System.out.println(topics.reversed()); // Java 21+: [Spring, Kafka, Java, JPA]Common mistake
Removing items inside a for-each loop throws ConcurrentModificationException. Use list.removeIf(...) or an Iterator's remove().
Under the hood
Big-O cheat sheet: ArrayList get is O(1), add at the end is amortized O(1), insert/remove in the middle is O(n). HashMap get/put are O(1) on average; TreeMap is O(log n). LinkedList has O(n) access and poor cache locality, so ArrayDeque beats it even as a queue. List.of collections reject nulls and throw UnsupportedOperationException if modified.
Quick decision guide:
Quick decision guide:
- ArrayList: read by index / iterate often; avoid repeated front inserts.
- LinkedList: only consider when you already hold a ListIterator at the insertion point and do many local edits; otherwise usually not worth it.
- HashSet: membership/deduplication; no predictable iteration order.
- LinkedHashSet: unique values but preserve insertion order (e.g., unique recent search terms).
- TreeSet: unique values kept sorted; range queries such as `ceiling`, `floor`, `headSet`.
- HashMap: key lookup/counting/cache; no iteration-order promise.
- LinkedHashMap: predictable insertion order or access-order LRU cache.
- TreeMap: sorted keys and range navigation (e.g., events by timestamp).
- ArrayDeque: efficient FIFO queue or LIFO stack in one thread.
- PriorityQueue: repeatedly retrieve the best/smallest item; iteration itself is not sorted.,
- ConcurrentHashMap: shared map updated by multiple threads; it does not make compound workflows automatically atomic.
Check yourself
Which structure keeps its keys sorted?
How this connects
Know these first
Part of Java from zero, Job-ready backend developer, Crack the Java interview, Java 8 and collections, practically.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.