Chapter 18: Collections Framework
In real-world applications (especially in Mumbai’s booming tech scene ☕), you almost never use plain arrays for lists of items. Instead, you use Collections — dynamic, rich, and ready-to-use data structures.
The Java Collections Framework (in package java.util) gives you:
- Ready-made classes for lists, sets, maps, queues, etc.
- Tons of useful methods (add, remove, sort, search, iterate…)
- Thread-safe options, performance-tuned implementations
We’ll go super slowly, like we’re sitting together in a Bandra café with cutting chai, and I’ll explain everything with real-life analogies, complete runnable programs, step-by-step breakdowns, tables, common mistakes, and tons of examples you can copy-paste and run right now.
Let’s dive in!
1. Overview of Collections Framework
Main Interfaces (the blueprints):
| Interface | Purpose | Ordered? | Allows Duplicates? | Allows null? | Example Use Case |
|---|---|---|---|---|---|
| List | Ordered collection (index-based) | Yes | Yes | Yes | Shopping list, playlist |
| Set | No duplicates | No (except some implementations) | No | Yes (except TreeSet) | Unique tags, user IDs |
| Map | Key-Value pairs | No (except some) | Keys unique | Yes (keys & values) | Dictionary, cache |
| Queue | FIFO (First-In-First-Out) | Yes | Yes | Yes | Task queue, printer jobs |
| Deque | Double-ended queue (add/remove from both ends) | Yes | Yes | Yes | Undo/redo stack, browser history |
Common Implementations:
| Interface | Implementations (most used) | Ordered? | Performance Notes |
|---|---|---|---|
| List | ArrayList, LinkedList, Vector (old) | Yes | ArrayList → fast random access LinkedList → fast add/remove |
| Set | HashSet, LinkedHashSet, TreeSet | No / Insertion / Sorted | HashSet → fastest TreeSet → always sorted |
| Map | HashMap, LinkedHashMap, TreeMap | No / Insertion / Sorted | HashMap → fastest TreeMap → sorted by keys |
2. List – Ordered, Indexed, Duplicates Allowed
A. ArrayList (Most common – backed by dynamic array)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.util.ArrayList; import java.util.List; public class ArrayListDemo { public static void main(String[] args) { // Create ArrayList List<String> cities = new ArrayList<>(); // Add elements cities.add("Mumbai"); cities.add("Delhi"); cities.add("Bangalore"); cities.add("Mumbai"); // Duplicates allowed cities.add(1, "Pune"); // Insert at index 1 // Size & access System.out.println("Size: " + cities.size()); // 5 System.out.println("City at index 2: " + cities.get(2)); // Bangalore // Remove cities.remove("Delhi"); // by object cities.remove(0); // by index // Iterate using for-each (recommended) System.out.println("\nCities:"); for (String city : cities) { System.out.println(city); } // Check contains System.out.println("Contains Mumbai? " + cities.contains("Mumbai")); // true } } |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
Size: 5 City at index 2: Bangalore Cities: Pune Bangalore Mumbai Contains Mumbai? true |
B. LinkedList (Doubly-linked list – fast add/remove at ends)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.LinkedList; import java.util.Queue; public class LinkedListDemo { public static void main(String[] args) { LinkedList<String> tasks = new LinkedList<>(); // Add at both ends tasks.add("Task 1"); // add last tasks.addFirst("Urgent Task"); // add at beginning tasks.addLast("Task 2"); System.out.println("First: " + tasks.getFirst()); // Urgent Task System.out.println("Last: " + tasks.getLast()); // Task 2 // Remove from both ends tasks.removeFirst(); // removes Urgent Task tasks.removeLast(); // removes Task 2 System.out.println("Remaining: " + tasks); } } |
3. Set – No Duplicates
A. HashSet (Fastest, no order)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.HashSet; import java.util.Set; public class HashSetDemo { public static void main(String[] args) { Set<String> uniqueNames = new HashSet<>(); uniqueNames.add("Webliance"); uniqueNames.add("Amit"); uniqueNames.add("Webliance"); // Ignored – duplicate! uniqueNames.add("Priya"); System.out.println("Unique names: " + uniqueNames); // Order not guaranteed System.out.println("Size: " + uniqueNames.size()); // 3 } } |
B. LinkedHashSet (Insertion order preserved)
|
0 1 2 3 4 5 6 7 8 9 10 |
Set<String> orderedSet = new LinkedHashSet<>(); orderedSet.add("Mumbai"); orderedSet.add("Delhi"); orderedSet.add("Bangalore"); System.out.println(orderedSet); // [Mumbai, Delhi, Bangalore] |
C. TreeSet (Always sorted – natural order or custom Comparator)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.TreeSet; TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(50); numbers.add(10); numbers.add(30); System.out.println(numbers); // [10, 30, 50] – sorted! |
4. Map – Key-Value Pairs
A. HashMap (Fastest, no order)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.HashMap; import java.util.Map; public class HashMapDemo { public static void main(String[] args) { Map<String, Integer> marks = new HashMap<>(); marks.put("Webliance", 95); marks.put("Amit", 88); marks.put("Priya", 92); marks.put("Webliance", 98); // Overwrites old value // Access System.out.println("Webliance marks: " + marks.get("Webliance")); // 98 // Iterate System.out.println("\nAll students:"); for (Map.Entry<String, Integer> entry : marks.entrySet()) { System.out.println(entry.getKey() + " → " + entry.getValue()); } } } |
B. LinkedHashMap (Insertion order)
|
0 1 2 3 4 5 6 7 8 9 10 |
Map<String, String> lhm = new LinkedHashMap<>(); lhm.put("A", "Apple"); lhm.put("B", "Banana"); lhm.put("C", "Cherry"); System.out.println(lhm); // {A=Apple, B=Banana, C=Cherry} |
C. TreeMap (Sorted by keys)
|
0 1 2 3 4 5 6 7 8 9 10 |
Map<Integer, String> tm = new TreeMap<>(); tm.put(3, "Three"); tm.put(1, "One"); tm.put(2, "Two"); System.out.println(tm); // {1=One, 2=Two, 3=Three} |
5. Queue & Deque
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.LinkedList; import java.util.Queue; import java.util.Deque; public class QueueDemo { public static void main(String[] args) { Queue<String> queue = new LinkedList<>(); queue.add("Task1"); queue.add("Task2"); queue.add("Task3"); System.out.println("First task: " + queue.poll()); // Task1 (removes) System.out.println("Next: " + queue.peek()); // Task2 (just peeks) // Deque – can add/remove from both ends Deque<String> history = new LinkedList<>(); history.addFirst("Page1"); history.addLast("Page2"); System.out.println(history); // [Page1, Page2] } } |
6. Iterators & For-Each Loop
For-each (enhanced for loop) – cleanest way to read collections
|
0 1 2 3 4 5 6 7 8 9 10 |
List<String> fruits = new ArrayList<>(List.of("Apple", "Banana", "Cherry")); for (String fruit : fruits) { System.out.println(fruit); } |
Iterator – more control (remove while iterating)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
Iterator<String> it = fruits.iterator(); while (it.hasNext()) { String fruit = it.next(); if (fruit.equals("Banana")) { it.remove(); // Safe removal } } |
Quick Recap Table (Your Cheat Sheet)
| Collection | Best For | Duplicates? | Ordered? | Sorted? | Null? |
|---|---|---|---|---|---|
| ArrayList | Fast random access, general list | Yes | Yes | No | Yes |
| LinkedList | Fast add/remove at ends | Yes | Yes | No | Yes |
| HashSet | Fast lookup, unique items | No | No | No | Yes |
| TreeSet | Unique + always sorted | No | No | Yes | No |
| HashMap | Fast key-value lookup | Keys unique | No | No | Yes |
| TreeMap | Sorted keys | Keys unique | No | Yes | Yes |
Homework for You (Practice to Master!)
- Basic: Create an ArrayList of 5 city names → print them using for-each.
- Medium: Use HashMap to store student names & marks → print all with for-each on entrySet.
- Advanced: Create TreeSet of integers → add 10 random numbers → print sorted list.
- Fun: Use LinkedList as a queue → simulate a ticket counter (add people, serve them).
- Challenge: Remove all even numbers from an ArrayList using Iterator.
You’re doing fantastic! Collections are the Swiss Army knife of Java — now you can handle any kind of data like a pro.
