Choosing the right collection
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Choosing a collection means asking what the data needs: a fixed order, no duplicates, lookup by a key, or first come, first served. The answers point to a List, a Set, a Map or a Queue, and then to one class inside that family.
Four questions pick the family
Ask these questions in this order. The first "yes" decides the family.
- Do I find things by a key, like a roll number or a PNR? →
Map. - Must every item be unique, like transaction ids or registered emails? →
Set. - Do I handle items one at a time, in arrival order, like tokens or print jobs? →
Queue. - Otherwise: an ordered group with positions, duplicates allowed →
List.
Example 1 · A list lets duplicates in, a set does not
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;
public class DuplicatePaymentDemo { public static void main(String[] args) { String[] payments = {"TXN501", "TXN502", "TXN501", "TXN503", "TXN502"};
List<String> asList = new ArrayList<>(); Set<String> asSet = new HashSet<>(); for (String id : payments) { asList.add(id); boolean isNew = asSet.add(id); if (!isNew) { System.out.println("Duplicate payment blocked: " + id); } } System.out.println("List stored " + asList.size() + " payments"); System.out.println("Set stored " + asSet.size() + " payments"); }}Duplicate payment blocked: TXN501 Duplicate payment blocked: TXN502 List stored 5 payments Set stored 3 payments
What this code does
- A UPI app must never record the same transaction twice. The list happily stores all 5 ids, duplicates included.
Set.addreturnsfalsewhen the item is already there, so one call both checks and stores. Must items be unique? That question points to aSet.
Example 2 · Searching a list vs asking a map
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class LookupDemo { public static void main(String[] args) { List<String> records = new ArrayList<>(); records.add("R101:Aarav"); records.add("R102:Priya"); records.add("R103:Rohan"); records.add("R104:Kavya"); records.add("R105:Arjun");
// List: check records one by one int checks = 0; for (String r : records) { checks++; if (r.startsWith("R104:")) { System.out.println("List: " + r.substring(5) + " after " + checks + " checks"); break; } }
// Map: jump straight to the value by its key Map<String, String> byRoll = new HashMap<>(); byRoll.put("R101", "Aarav"); byRoll.put("R102", "Priya"); byRoll.put("R103", "Rohan"); byRoll.put("R104", "Kavya"); byRoll.put("R105", "Arjun"); System.out.println("Map: " + byRoll.get("R104") + " in one call"); System.out.println("Map: " + byRoll.get("R999")); }}List: Kavya after 4 checks Map: Kavya in one call Map: null
What this code does
- To find R104 in the list, the loop checks records one by one. With 50,000 students it could need 50,000 checks.
- The map goes straight to the value using the key. A missing key gives
null. Do I look things up by a key? That question points to aMap.
Example 3 · A queue serves in arrival order
import java.util.ArrayDeque;import java.util.Queue;
public class OrderQueueDemo { public static void main(String[] args) { Queue<String> orders = new ArrayDeque<>(); orders.offer("#101 Laptop"); orders.offer("#102 Mouse"); orders.offer("#103 Keyboard"); System.out.println("Next up: " + orders.peek());
System.out.println("Packing " + orders.poll()); System.out.println("Packing " + orders.poll()); orders.offer("#104 Monitor"); // a new order joins at the back System.out.println("Waiting: " + orders); System.out.println("Packing " + orders.poll()); System.out.println("Packing " + orders.poll()); System.out.println("Empty? " + orders.isEmpty()); }}Next up: #101 Laptop Packing #101 Laptop Packing #102 Mouse Waiting: [#103 Keyboard, #104 Monitor] Packing #103 Keyboard Packing #104 Monitor Empty? true
What this code does
offeradds at the back,pollremoves from the front, andpeekonly looks at the front. The first order to come is the first packed: FIFO, first in, first out.- No index juggling is needed. Do I process items one at a time, in arrival order? That points to a
Queue. The Queues module covers it in depth.
ArrayList for lists and HashMap for maps. They are the right answer most of the time.Then pick the class
Each family has a few classes. They keep the same promise, but differ in order and speed. Here is one declaration per family.
List<String> cart = new ArrayList<>();Set<String> tags = new LinkedHashSet<>();Map<String, Integer> stock = new TreeMap<>();Queue<String> orders = new ArrayDeque<>();List:ArrayListis the default.LinkedListis rarely better; the Lists module explains why.Set:HashSet(fastest, no order),LinkedHashSet(insertion order),TreeSet(sorted).Map:HashMap(fastest, no order),LinkedHashMap(insertion order),TreeMap(sorted keys).Queue:ArrayDequefor first in, first out;PriorityQueuewhen the smallest (or most urgent) item must come out first.
Example 4 · Same family, different order: LinkedHashSet vs TreeSet
import java.util.LinkedHashSet;import java.util.Set;import java.util.TreeSet;
public class VisitorsDemo { public static void main(String[] args) { String[] gateLog = {"Rohan", "Aarav", "Priya", "Aarav", "Divya", "Rohan"};
Set<String> byArrival = new LinkedHashSet<>(); Set<String> byName = new TreeSet<>(); for (String name : gateLog) { byArrival.add(name); byName.add(name); } System.out.println("Unique visitors: " + byArrival.size()); System.out.println("In arrival order: " + byArrival); System.out.println("In A-Z order: " + byName); }}Unique visitors: 4 In arrival order: [Rohan, Aarav, Priya, Divya] In A-Z order: [Aarav, Divya, Priya, Rohan]
What this code does
- Both are sets, so each visitor appears once. The question that picks the class is: what order do I need?
LinkedHashSetkeeps arrival order.TreeSetkeeps items sorted.HashSetpromises no order at all, but it is the fastest; use it when order does not matter.
The interface stays on the left, so changing the class on the right later does not touch the rest of the code.
Big-O in plain words
Big-O describes how the work grows as the data grows. It ignores small details and looks only at the trend, such as O(1), O(log n) or O(n).
Three sizes of work appear again and again: O(1), O(log n) and O(n).
List<Integer> rolls = new ArrayList<>(List.of(101, 102, 103));rolls.get(2); // O(1): jumps straight to slot 2rolls.contains(103); // O(n): checks the items one by oneSet<Integer> rollSet = new HashSet<>(rolls);rollSet.contains(103); // O(1) on average: goes to one bucketTreeSet<Integer> sorted = new TreeSet<>(rolls);sorted.contains(103); // O(log n): about 20 steps for 10 lakh itemsO(1), constant: about the same time for 10 items or 10 lakh items, like opening page 50 of a book directly. O(log n): grows very slowly, about 20 steps for 10 lakh items, like finding a word in a dictionary by halves. O(n), linear: time grows with the size, like reading every page to find one name.
ArrayList:get(i)O(1), add at the end O(1) usually,containsO(n), remove from the front O(n).HashSet/HashMap: add,contains/get, remove are O(1) on average.TreeSet/TreeMap: add,contains/get, remove are O(log n), and items stay sorted.ArrayDeque: add or remove at either end is O(1).
get(2) jumps straight to a slot, but contains on a list may check every item. A HashSet goes to one bucket, and a TreeSet halves the search at each step.
Real scenarios
Most choices become easy once you say the need in one line. Each need then becomes one declaration.
List<String> attendance = new ArrayList<>(); // roll-call order, repeats allowedSet<String> upiIds = new HashSet<>(); // unique ids, fast duplicate checkMap<Integer, Integer> marksByRoll = new HashMap<>(); // roll number -> marksMap<Integer, Integer> report = new TreeMap<>(); // same, sorted by roll numberQueue<String> orders = new ArrayDeque<>(); // orders packed in arrival orderQueue<Integer> tickets = new PriorityQueue<>(); // most urgent first- Attendance in roll-call order, names may repeat across days →
List(ArrayList). - Unique UPI transaction ids, fast duplicate check →
Set(HashSet). - Roll number → marks, frequent lookups →
Map(HashMap); for a report sorted by roll number →TreeMap. - Online orders packed in the order they arrive →
Queue(ArrayDeque); support tickets by urgency →PriorityQueue.
Trace the code
Trace orders through a queue and a set
Variables
- orders
- []
Output
(nothing printed yet)Line 8The queue is empty. It will hand out orders in the order they arrived.
The common trap: a list used for lookups
A common trap is to put everything in an ArrayList and call contains again and again. With 20 items nobody notices; with 1 lakh items the program crawls, because every search is O(n).
Example 5 · Big-O you can feel: contains on a list vs a set
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;
public class SpeedDemo { public static void main(String[] args) { List<Integer> idList = new ArrayList<>(); Set<Integer> idSet = new HashSet<>(); for (int i = 0; i < 100000; i++) { idList.add(i); idSet.add(i); }
long start = System.nanoTime(); int found = 0; for (int i = 0; i < 5000; i++) { if (idList.contains(99999 - i)) { found++; } } long listMs = (System.nanoTime() - start) / 1_000_000; System.out.println("List found " + found + " in " + listMs + " ms");
start = System.nanoTime(); found = 0; for (int i = 0; i < 5000; i++) { if (idSet.contains(99999 - i)) { found++; } } long setMs = (System.nanoTime() - start) / 1_000_000; System.out.println("Set found " + found + " in " + setMs + " ms"); }}List found 5000 in 742 ms Set found 5000 in 0 ms
What this code does
- Both hold the same 1 lakh ids and answer the same 5,000 questions. The list scans its items for each question, so it takes hundreds of milliseconds. The set takes almost no time.
- This is O(n) against O(1). Your times will differ by computer, but the gap stays huge, and it grows as the data grows.
If your code keeps asking "is it there?" or "what belongs to this key?", a Set or a Map is the right home for the data. Keep the list too if you also need its order.
Next step
Check your understanding
11 quick questions