Programming in Java
Unit 13: Collections Framework
Master Java's powerful Collections Framework โ from ArrayList to HashMap internals โ and build production-grade data management systems used at Flipkart, IRCTC, and every Indian tech company.
โฑ๏ธ 8 hrs theory + 6 hrs lab | ๐ฐ Earning Potential: โน10Kโโน30K/month | ๐ 30 MCQs (Bloom's Mapped)
๐ผ Jobs this unlocks: Java Backend Developer (โน5โ10 LPA) | Software Engineer (โน6โ15 LPA) | Data Processing Developer (โน4โ8 LPA)
Opening Hook โ Flipkart Big Billion Day: How Collections Power India's Biggest Sale
๐ Behind the Scenes of Flipkart's Big Billion Day
Every year, Flipkart's Big Billion Day sale handles 50 million products in its catalog, 1.5 million orders per hour, and flash deals that expire in seconds. How does the system instantly find any product among 50 million? How does it countdown flash deals in perfect priority order? How does your cart grow and shrink dynamically?
The secret weapon: Java Collections Framework.
โข HashMap powers the product catalog โ 50 million products mapped by product ID, giving O(1) instant lookup. Search "iPhone 16"? HashMap finds it in constant time, whether there are 50 products or 50 million.
โข PriorityQueue manages the flash deal countdown โ deals expiring soonest automatically bubble to the top. No manual sorting needed.
โข ArrayList handles your cart โ dynamically growing as you add items, supporting instant access by index to display "Item 3 of 7 in your cart".
What if YOU built this? What if you could design systems that handle millions of data points with zero-lag lookups? That's exactly what this unit teaches you โ the data structures that power every serious Java application in India.
Learning Outcomes โ Bloom's Taxonomy Mapped (12 Outcomes)
| Bloom's Level | Learning Outcome |
|---|---|
| ๐ต Remember | LO1: List all core interfaces in the Collection hierarchy (Collection, List, Set, Queue, Map) and name at least two implementing classes for each |
| ๐ต Remember | LO2: State the time complexity of fundamental operations (add, get, remove, contains) for ArrayList, LinkedList, HashSet, and HashMap |
| ๐ข Understand | LO3: Explain the internal working of HashMap โ hashing, buckets, linked list chaining, and tree conversion at threshold 8 |
| ๐ข Understand | LO4: Distinguish between Comparable (natural ordering) and Comparator (custom ordering) with real-world Indian examples |
| ๐ก Apply | LO5: Write a complete Student Result Management System using ArrayList, HashMap, and Collections.sort() |
| ๐ก Apply | LO6: Implement an IRCTC-style waitlist queue using LinkedList as a Queue with proper enqueue/dequeue operations |
| ๐ Analyze | LO7: Compare ArrayList vs LinkedList across 10 parameters and determine which is optimal for a given use case |
| ๐ Analyze | LO8: Analyze how HashSet internally uses HashMap and why it guarantees uniqueness |
| ๐ด Evaluate | LO9: Evaluate the trade-offs of using TreeMap vs HashMap vs LinkedHashMap for a Flipkart product catalog and justify the best choice |
| ๐ด Evaluate | LO10: Assess when to use Iterator vs ListIterator vs enhanced for-loop, considering ConcurrentModificationException risks |
| ๐ฃ Create | LO11: Design and code a complete Flipkart Product Catalog system using HashMap with CRUD operations |
| ๐ฃ Create | LO12: Build an LRU Cache using LinkedHashMap with access-order mode, suitable for interview-level demonstration |
Concept Explanation โ Java Collections Framework from Scratch
1. The Collection Hierarchy
Think of Java Collections Framework like a well-organised Indian railway system. Just as railways have different types of trains (Express, Local, Rajdhani) for different needs, Collections has different interfaces and classes for different data storage needs.
๐ The Collection Interface Hierarchy
Hierarchy // Collection Hierarchy (Iterable โ Collection โ List/Set/Queue) Iterable (root interface) โโโ Collection โโโ List (ordered, allows duplicates) โ โโโ ArrayList โ dynamic array, O(1) random access โ โโโ LinkedList โ doubly-linked list, O(1) insert/delete โ โโโ Vector โ synchronized (legacy, use ArrayList) โ โโโ Stack โ LIFO (legacy, use ArrayDeque) โ โโโ Set (no duplicates) โ โโโ HashSet โ unordered, O(1) ops, uses HashMap โ โโโ LinkedHashSetโ insertion-ordered, O(1) ops โ โโโ TreeSet โ sorted, O(log n) ops, uses TreeMap โ โโโ Queue (FIFO processing) โโโ PriorityQueueโ min-heap, O(log n) insert/remove โโโ Deque (double-ended queue) โโโ ArrayDeque โ resizable array, faster than Stack/LinkedList // Map Hierarchy (separate from Collection) Map (key-value pairs) โโโ HashMap โ unordered, O(1) ops, allows null key โโโ LinkedHashMap โ insertion/access ordered, O(1) ops โโโ TreeMap โ sorted by key, O(log n) ops โโโ Hashtable โ synchronized (legacy, use ConcurrentHashMap)
mom@ybl โ that's O(1) lookup, exactly like HashMap. Whether you have 5 contacts or 5,000, the lookup speed is constant.
Map<K,V> stores key-value pairs, while Collection<E> stores single elements. Don't write "Map implements Collection" in your exam โ it's wrong!
2. ArrayList vs LinkedList โ The 10-Parameter Showdown
Analogy: ArrayList is like a movie theatre โ seats are numbered (indexed), you can jump to seat 42 instantly, but inserting a new seat in the middle means shifting everyone. LinkedList is like a train โ each coach is linked to the next, adding/removing a coach in the middle is easy, but finding coach #42 means walking from the engine.
| # | Parameter | ArrayList | LinkedList |
|---|---|---|---|
| 1 | Internal Structure | Dynamic resizable array | Doubly-linked list (nodes) |
| 2 | Random Access (get) | O(1) โ direct index | O(n) โ must traverse |
| 3 | Add at End | O(1) amortized | O(1) |
| 4 | Add at Middle | O(n) โ shifts elements | O(1) โ pointer change (if position known) |
| 5 | Remove at Middle | O(n) โ shifts elements | O(1) โ pointer change (if position known) |
| 6 | Memory Overhead | Lower โ contiguous array | Higher โ each node stores prev/next pointers |
| 7 | Cache Performance | Excellent โ locality of reference | Poor โ nodes scattered in heap |
| 8 | Implements Queue/Deque? | โ No | โ Yes โ implements Deque |
| 9 | Thread Safety | Not synchronized | Not synchronized |
| 10 | Best Use Case | Read-heavy (90% of cases) | Insert/delete-heavy, queue/deque needs |
Java // ArrayList โ Flipkart Cart Example import java.util.ArrayList; public class FlipkartCart { public static void main(String[] args) { ArrayList<String> cart = new ArrayList<>(); // Adding items to cart โ O(1) amortized cart.add("iPhone 16 Pro"); // index 0 cart.add("Samsung Galaxy S24"); // index 1 cart.add("OnePlus Nord 4"); // index 2 cart.add("Boat Airdopes 441"); // index 3 // Random access โ O(1) System.out.println("Item 2: " + cart.get(1)); // Samsung Galaxy S24 // Remove item โ O(n) shifts remaining cart.remove("Samsung Galaxy S24"); // Iterate cart System.out.println("=== Your Flipkart Cart ==="); for (int i = 0; i < cart.size(); i++) { System.out.println((i+1) + ". " + cart.get(i)); } System.out.println("Total items: " + cart.size()); } }
3. HashSet, TreeSet, LinkedHashSet โ No Duplicates Allowed
Analogy: Think of Set like Aadhaar numbers โ every Indian gets exactly ONE unique number. You can't have two people with the same Aadhaar. That's what Set does โ guarantees uniqueness.
| Set Type | Order | Performance | Null? | Use Case |
|---|---|---|---|---|
| HashSet | No order guaranteed | O(1) add/remove/contains | 1 null | Fast uniqueness check โ "Has this email been registered?" |
| LinkedHashSet | Insertion order preserved | O(1) add/remove/contains | 1 null | Unique items where order matters โ recent search history |
| TreeSet | Sorted (natural/comparator) | O(log n) all ops | No null | Sorted unique data โ leaderboard scores, alphabetical names |
Java // HashSet โ Unique voter IDs at a booth import java.util.*; public class VoterBooth { public static void main(String[] args) { Set<String> voters = new HashSet<>(); voters.add("VOTER001"); voters.add("VOTER002"); voters.add("VOTER003"); voters.add("VOTER001"); // โ Duplicate โ silently ignored! System.out.println("Total unique voters: " + voters.size()); // 3 System.out.println("VOTER001 voted? " + voters.contains("VOTER001")); // true // TreeSet โ sorted leaderboard TreeSet<Integer> scores = new TreeSet<>(); scores.add(85); scores.add(92); scores.add(78); scores.add(95); System.out.println("Sorted scores: " + scores); // [78, 85, 92, 95] System.out.println("Topper: " + scores.last()); // 95 System.out.println("Lowest: " + scores.first()); // 78 } }
hashSet.add("VOTER001"), it internally does hashMap.put("VOTER001", DUMMY_OBJECT). The keys are your Set elements, and all values point to the same dummy constant object PRESENT. This is why HashSet has O(1) performance โ it piggybacks on HashMap's hashing.
4. PriorityQueue & ArrayDeque
Analogy: PriorityQueue is like an emergency room (ER) at AIIMS Delhi โ patients aren't treated first-come-first-served. The most critical patient (highest priority) is treated first, regardless of arrival time. ArrayDeque is like a Mumbai local train door โ people can enter and exit from both ends.
Java // PriorityQueue โ IRCTC Flash Deal Countdown import java.util.*; public class FlashDealCountdown { public static void main(String[] args) { // Min-heap: deal expiring soonest comes first PriorityQueue<String> dealQueue = new PriorityQueue<>( (a, b) -> { int minA = Integer.parseInt(a.split(":")[0]); int minB = Integer.parseInt(b.split(":")[0]); return minA - minB; } ); dealQueue.add("5:iPhone 16 - โน59,999"); dealQueue.add("2:Boat Earbuds - โน499"); dealQueue.add("10:Samsung TV - โน29,999"); dealQueue.add("1:Mi Band - โน999"); System.out.println("=== Flash Deals (Expiring Soonest First) ==="); while (!dealQueue.isEmpty()) { String deal = dealQueue.poll(); // removes and returns head System.out.println("โฐ Expiring in " + deal.split(":")[0] + " min โ " + deal.split(":")[1]); } } }
Java // ArrayDeque โ Faster than Stack and LinkedList import java.util.*; public class BrowserHistory { public static void main(String[] args) { // Use ArrayDeque as Stack (LIFO) Deque<String> history = new ArrayDeque<>(); history.push("flipkart.com"); history.push("flipkart.com/mobiles"); history.push("flipkart.com/iphone-16"); System.out.println("Current page: " + history.peek()); // iphone-16 history.pop(); // Go back System.out.println("After back: " + history.peek()); // /mobiles } }
5. HashMap โ Internal Working (Interview Favourite)
Plain English: Imagine a library with 16 shelves (buckets). When you bring a new book, the librarian runs the book title through a formula (hash function) that produces a shelf number. The book goes on that shelf. When you ask for it later, same formula โ same shelf โ instant retrieval.
๐ง HashMap Internals โ How It Really Works
Step 1 โ Hashing: When you do map.put("iPhone", 59999), Java calls "iPhone".hashCode() which returns an integer (e.g., -2077747470). This is then compressed: index = hash & (n-1) where n = number of buckets (default 16).
Step 2 โ Bucket Storage: The computed index (0โ15) determines which bucket the entry goes into. Each bucket is initially a linked list of Node<K,V> objects.
Step 3 โ Collision Handling: If two keys hash to the same bucket (collision), the new entry is appended to the linked list in that bucket. This is called chaining.
Step 4 โ Treeification (Java 8+): When a single bucket's linked list grows beyond 8 nodes (TREEIFY_THRESHOLD), it converts to a balanced Red-Black Tree, improving worst-case from O(n) to O(log n).
Step 5 โ Resizing: When total entries exceed capacity ร loadFactor (default: 16 ร 0.75 = 12), HashMap doubles its bucket array to 32 and rehashes all entries.
Internals // HashMap Internal Structure (Java 8+) Bucket Array (Node<K,V>[]) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ [0] โ null โ โ [1] โ Node("Milk",40) โ null โ โ [2] โ null โ โ [3] โ Node("Rice",60) โ Node("Dal",80) โ nullโ โ collision chain โ [4] โ null โ โ ... โ โ [7] โ ๐ณ Red-Black Tree (if > 8 nodes) โ โ treeified bucket โ ... โ โ[15] โ Node("Bread",35) โ null โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Default capacity: 16 buckets Load factor: 0.75 (resize when 75% full) TREEIFY_THRESHOLD: 8 (linked list โ tree)
put() traverses the linked list/tree in that bucket, comparing keys with .equals(). If a matching key is found, the value is updated. If not, a new Node is appended. This is why you MUST override both hashCode() AND equals() when using custom objects as keys.
Java // Full Code: FlipkartCatalog using HashMap import java.util.*; public class FlipkartCatalog { static HashMap<String, Double> catalog = new HashMap<>(); static Scanner sc = new Scanner(System.in); public static void main(String[] args) { // Pre-load catalog catalog.put("PROD001", 59999.0); // iPhone 16 catalog.put("PROD002", 24999.0); // Samsung Galaxy M34 catalog.put("PROD003", 1499.0); // Boat Rockerz 450 catalog.put("PROD004", 34999.0); // HP Laptop 15s catalog.put("PROD005", 999.0); // Mi Band 8 int choice; do { System.out.println("\n=== Flipkart Product Catalog ==="); System.out.println("1. Add Product"); System.out.println("2. Search Product by ID"); System.out.println("3. Update Price"); System.out.println("4. Remove Product"); System.out.println("5. Display All Products"); System.out.println("6. Exit"); System.out.print("Choice: "); choice = sc.nextInt(); sc.nextLine(); switch (choice) { case 1: addProduct(); break; case 2: searchProduct(); break; case 3: updatePrice(); break; case 4: removeProduct(); break; case 5: displayAll(); break; } } while (choice != 6); } static void addProduct() { System.out.print("Product ID: "); String id = sc.nextLine(); System.out.print("Price (โน): "); double price = sc.nextDouble(); catalog.put(id, price); // O(1) System.out.println("โ Product added!"); } static void searchProduct() { System.out.print("Enter Product ID: "); String id = sc.nextLine(); if (catalog.containsKey(id)) { // O(1) System.out.println("โ Found! Price: โน" + catalog.get(id)); } else { System.out.println("โ Product not found."); } } static void updatePrice() { System.out.print("Product ID: "); String id = sc.nextLine(); if (catalog.containsKey(id)) { System.out.print("New price (โน): "); catalog.put(id, sc.nextDouble()); // O(1) โ replaces old value System.out.println("โ Price updated!"); } else { System.out.println("โ Product not found."); } } static void removeProduct() { System.out.print("Product ID: "); String id = sc.nextLine(); if (catalog.remove(id) != null) { // O(1) System.out.println("โ Product removed."); } else { System.out.println("โ Product not found."); } } static void displayAll() { System.out.println("\n--- All Products ---"); for (Map.Entry<String, Double> entry : catalog.entrySet()) { System.out.printf("%-10s โ โน%,.0f%n", entry.getKey(), entry.getValue()); } System.out.println("Total products: " + catalog.size()); } }
6. TreeMap & LinkedHashMap
| Feature | HashMap | TreeMap | LinkedHashMap |
|---|---|---|---|
| Order | No order | Sorted by key (natural/comparator) | Insertion order (or access order) |
| Performance | O(1) avg | O(log n) โ Red-Black Tree | O(1) avg |
| Null key? | โ 1 null key | โ No null key | โ 1 null key |
| Internal Structure | Array + Linked List/Tree | Red-Black Tree | HashMap + Doubly-Linked List |
| Best For | General purpose | Range queries, sorted keys | LRU Cache, ordered iteration |
Java // TreeMap โ Student marks sorted by name import java.util.*; public class SortedStudentMarks { public static void main(String[] args) { TreeMap<String, Integer> marks = new TreeMap<>(); marks.put("Aarav", 92); marks.put("Zara", 88); marks.put("Kishore", 95); marks.put("Diya", 91); marks.put("Meena", 87); System.out.println("Alphabetical order: " + marks); System.out.println("First (A): " + marks.firstKey()); // Aarav System.out.println("Last (Z): " + marks.lastKey()); // Zara System.out.println("D-M range: " + marks.subMap("D", "N")); // Diya, Kishore, Meena } }
7. Collections Utility Class
The Collections class (note the 's' โ it's different from Collection interface) provides static utility methods for operating on collections:
Java import java.util.*; public class CollectionsDemo { public static void main(String[] args) { List<Integer> marks = new ArrayList<>(Arrays.asList(78, 92, 45, 88, 65)); Collections.sort(marks); // [45, 65, 78, 88, 92] Collections.reverse(marks); // [92, 88, 78, 65, 45] Collections.shuffle(marks); // random order System.out.println("Max: " + Collections.max(marks)); // 92 System.out.println("Min: " + Collections.min(marks)); // 45 System.out.println("Freq of 78: " + Collections.frequency(marks, 78)); // Unmodifiable collection โ immutable wrapper List<String> states = Collections.unmodifiableList( Arrays.asList("Maharashtra", "Karnataka", "Tamil Nadu") ); // states.add("Kerala"); โ throws UnsupportedOperationException! } }
8. Iterator & ListIterator
| Feature | Iterator | ListIterator | Enhanced for-loop |
|---|---|---|---|
| Direction | Forward only | Forward + Backward | Forward only |
| Remove during iteration? | โ
Yes โ it.remove() | โ Yes | โ No โ ConcurrentModificationException |
| Add during iteration? | โ No | โ
Yes โ it.add() | โ No |
| Works with | All Collections | List only | All Iterable |
| Get index? | โ No | โ
Yes โ nextIndex() | โ No |
Java // Safe removal during iteration โ Iterator import java.util.*; public class SafeRemoval { public static void main(String[] args) { List<Integer> marks = new ArrayList<>(Arrays.asList(85, 32, 91, 28, 76, 44)); // โ WRONG: ConcurrentModificationException // for (int m : marks) { if (m < 40) marks.remove(Integer.valueOf(m)); } // โ CORRECT: Use Iterator Iterator<Integer> it = marks.iterator(); while (it.hasNext()) { if (it.next() < 40) { it.remove(); // Safe removal! } } System.out.println("Passing marks: " + marks); // [85, 91, 76, 44] } }
list.remove() inside for (Type x : list) throws ConcurrentModificationException. Always use Iterator.remove() or list.removeIf() (Java 8+) instead.
9. Comparable vs Comparator
| Feature | Comparable | Comparator |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T o) | compare(T o1, T o2) |
| Modifies class? | Yes โ class must implement it | No โ external, separate class/lambda |
| Sorting count | Single natural ordering | Multiple custom orderings |
| Usage | Collections.sort(list) | Collections.sort(list, comparator) |
| Analogy | Default sort = Alphabetical roll call | Custom sort = Sort by marks, attendance, etc. |
Java // Full Code: StudentResultSystem โ Comparable + Comparator import java.util.*; class Student implements Comparable<Student> { String name; int rollNo; double percentage; Student(String name, int rollNo, double percentage) { this.name = name; this.rollNo = rollNo; this.percentage = percentage; } // Natural ordering: by roll number public int compareTo(Student other) { return this.rollNo - other.rollNo; } public String toString() { return String.format("Roll#%d %-12s %.1f%%", rollNo, name, percentage); } } public class StudentResultSystem { public static void main(String[] args) { List<Student> students = new ArrayList<>(); students.add(new Student("Aarav Patel", 103, 87.5)); students.add(new Student("Sneha Iyer", 101, 92.3)); students.add(new Student("Rohit Kumar", 105, 78.9)); students.add(new Student("Diya Sharma", 102, 95.1)); students.add(new Student("Kishore Nair", 104, 88.7)); // Sort by roll number (Comparable โ natural order) Collections.sort(students); System.out.println("=== Sorted by Roll Number (Comparable) ==="); students.forEach(System.out::println); // Sort by percentage descending (Comparator โ custom order) students.sort((s1, s2) -> Double.compare(s2.percentage, s1.percentage)); System.out.println("\n=== Sorted by Percentage Descending (Comparator) ==="); students.forEach(System.out::println); // Sort by name alphabetically (Comparator) students.sort(Comparator.comparing(s -> s.name)); System.out.println("\n=== Sorted by Name (Comparator) ==="); students.forEach(System.out::println); // Store in HashMap for O(1) lookup by roll number HashMap<Integer, Student> studentMap = new HashMap<>(); for (Student s : students) { studentMap.put(s.rollNo, s); } // Instant lookup System.out.println("\n๐ Lookup Roll#103: " + studentMap.get(103)); } }
10. Full Code: IRCTC Waitlist System
Java // IRCTC Waitlist System using LinkedList as Queue import java.util.*; class Passenger { String pnr, name; int age; String status; // CONFIRMED, WAITLIST, RAC Passenger(String pnr, String name, int age) { this.pnr = pnr; this.name = name; this.age = age; this.status = "WAITLIST"; } public String toString() { return String.format("PNR: %s | %-15s | Age: %d | Status: %s", pnr, name, age, status); } } public class IRCTCWaitlist { static final int MAX_CONFIRMED = 5; static List<Passenger> confirmed = new ArrayList<>(); static Queue<Passenger> waitlist = new LinkedList<>(); static Map<String, Passenger> pnrMap = new HashMap<>(); static int pnrCounter = 1000; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int choice; do { System.out.println("\n๐ === IRCTC Booking System ==="); System.out.println("1. Book Ticket"); System.out.println("2. Cancel Ticket (by PNR)"); System.out.println("3. Check PNR Status"); System.out.println("4. View All Passengers"); System.out.println("5. Exit"); System.out.print("Choice: "); choice = sc.nextInt(); sc.nextLine(); switch (choice) { case 1: System.out.print("Name: "); String name = sc.nextLine(); System.out.print("Age: "); int age = sc.nextInt(); bookTicket(name, age); break; case 2: System.out.print("Enter PNR: "); cancelTicket(sc.nextLine()); break; case 3: System.out.print("Enter PNR: "); checkPNR(sc.nextLine()); break; case 4: viewAll(); break; } } while (choice != 5); System.out.println("๐ Thank you for using IRCTC!"); } static void bookTicket(String name, int age) { String pnr = "PNR" + (++pnrCounter); Passenger p = new Passenger(pnr, name, age); if (confirmed.size() < MAX_CONFIRMED) { p.status = "CONFIRMED"; confirmed.add(p); System.out.println("โ CONFIRMED! PNR: " + pnr); } else { p.status = "WL/" + (waitlist.size() + 1); waitlist.add(p); // enqueue at end System.out.println("โณ WAITLISTED (" + p.status + ") PNR: " + pnr); } pnrMap.put(pnr, p); // O(1) lookup later } static void cancelTicket(String pnr) { Passenger p = pnrMap.get(pnr); if (p == null) { System.out.println("โ PNR not found."); return; } if (p.status.equals("CONFIRMED")) { confirmed.remove(p); // Promote first waitlisted passenger if (!waitlist.isEmpty()) { Passenger promoted = waitlist.poll(); // dequeue from front promoted.status = "CONFIRMED"; confirmed.add(promoted); System.out.println("๐ " + promoted.name + " promoted to CONFIRMED!"); } } else { waitlist.remove(p); } pnrMap.remove(pnr); System.out.println("โ Ticket " + pnr + " cancelled."); } static void checkPNR(String pnr) { Passenger p = pnrMap.get(pnr); // O(1) System.out.println(p != null ? p : "โ PNR not found."); } static void viewAll() { System.out.println("\n--- Confirmed (" + confirmed.size() + "/" + MAX_CONFIRMED + ") ---"); confirmed.forEach(System.out::println); System.out.println("--- Waitlist (" + waitlist.size() + ") ---"); waitlist.forEach(System.out::println); } }
Learn by Doing โ 3-Tier Lab: Student Result Management System
๐ข Tier 1 โ GUIDED: Student Result System with ArrayList & HashMap
Step 1: Create the Student class
Create a class Student with fields: rollNo (int), name (String), marks (int[5] for 5 subjects). Implement Comparable<Student> to sort by rollNo.
Step 2: Build the Management System
Use ArrayList<Student> to store all students and HashMap<Integer, Student> for O(1) lookup by roll number. Implement: Add, Search, Display All, Sort by Marks.
Step 3: Add Menu-Driven Interface
Use a do-while loop with Scanner for menu: 1) Add Student, 2) Search by Roll No, 3) Display All, 4) Sort by Percentage, 5) Top 3 Students, 6) Exit.
Step 4: Test with 5+ students
Add at least 5 Indian student names, sort by percentage, and find the topper.
Expected Output:
๐ก Tier 2 โ SEMI-GUIDED: Add Subject-Wise Analytics
Your Mission:
Extend the Tier 1 system with: subject-wise highest/lowest using TreeMap<String, TreeSet<Integer>>, pass/fail filter using Iterator (remove failed students into a separate list), and class average calculation.
Hints:
- Use
TreeMap<String, TreeSet<Integer>>where key = subject name, value = sorted set of marks - Use
Iteratorto safely remove students with percentage < 40% into afailedStudentslist - Use
Collections.max()andCollections.min()for class topper/weakest
Comparator to sort students by individual subject marks. E.g., "Show students sorted by Maths marks descending."
๐ด Tier 3 โ OPEN CHALLENGE: Full Flipkart Inventory System
The Brief:
Build a complete e-commerce inventory system with:
- Product Catalog:
HashMap<String, Product>โ CRUD operations with product ID as key - Category Index:
TreeMap<String, List<Product>>โ products grouped and sorted by category - Cart:
ArrayList<Product>with add/remove/total calculation - Order Queue:
PriorityQueueโ orders prioritised by order amount (highest first) - Unique Customers:
HashSet<Customer>โ no duplicate registrations - Search History:
LinkedHashSet<String>โ recent searches in order
Deliverable: A single Java file with all classes, menu-driven, with at least 10 pre-loaded products.
Problem Set
Syntax-Level Questions (5)
- Write the syntax to create an
ArrayListof Strings, add 3 elements, and print the element at index 1. - Write code to create a
HashMap<String, Integer>, insert 3 key-value pairs, and retrieve a value by key. - Write the syntax to iterate over a
HashSet<String>using an Iterator and print each element. - Write code to sort an
ArrayList<Integer>in descending order usingCollections.sort()with a Comparator. - Write the syntax to create a
PriorityQueue<Integer>(max-heap) and add 5 elements.
Programming Questions (8)
- Write a program that takes 10 names as input, stores them in an ArrayList, and displays them sorted alphabetically using
Collections.sort(). - Write a program that counts the frequency of each word in a paragraph using
HashMap<String, Integer>. - Write a program to remove all duplicate elements from an ArrayList using a HashSet.
- Implement a phone book using
TreeMap<String, String>(name โ phone number) that displays contacts in alphabetical order with search functionality. - Write a program to find the first non-repeating character in a string using
LinkedHashMap. - Implement a todo list using
LinkedListwith operations: addTask, removeTask, markComplete, displayPending. - Write a program that merges two sorted ArrayLists into a single sorted ArrayList without using
Collections.sort(). - Create a program that reads student names and marks from input, stores them in a
HashMap, and prints students who scored above average.
Industry-Level Problems (3) โ IRCTC Waitlist Theme
๐ Industry Problem 1: IRCTC Tatkal Queue Simulator
Simulate IRCTC's Tatkal booking: 100 passengers try to book 20 seats. Use PriorityQueue to prioritise by booking time (earlier = higher priority). If seats full, add to waitlist (Queue). When a confirmed passenger cancels, auto-promote from waitlist. Track using HashMap<PNR, Passenger>.
๐ Industry Problem 2: Train Route Station Tracker
Use LinkedHashMap<String, Integer> (station name โ distance from origin) to model the Delhi โ Chennai Rajdhani route. Support: display all stations in order, find distance between any two stations, list stations in a given range. Hint: Insertion order of LinkedHashMap preserves the station sequence.
๐ Industry Problem 3: Duplicate Ticket Detection
Given a list of 1000 booking entries (name + date + train), use HashSet to detect duplicate bookings (same person booking same train on same date). Report all duplicates with count using HashMap<String, Integer>.
Interview-Level Problems (3) โ LRU Cache Theme
๐ผ Interview Problem 1: LRU Cache using LinkedHashMap
Problem: Design an LRU (Least Recently Used) Cache of capacity K. Support get(key) and put(key, value) in O(1). When cache is full, evict the least recently used entry.
Hint: Use LinkedHashMap with accessOrder = true and override removeEldestEntry().
Java import java.util.*; class LRUCache<K, V> extends LinkedHashMap<K, V> { private final int capacity; public LRUCache(int capacity) { super(capacity, 0.75f, true); // accessOrder = true! this.capacity = capacity; } protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; // evict when over capacity } public static void main(String[] args) { LRUCache<String, String> cache = new LRUCache<>(3); cache.put("user1", "Aarav"); cache.put("user2", "Sneha"); cache.put("user3", "Kishore"); System.out.println(cache); // {user1=Aarav, user2=Sneha, user3=Kishore} cache.get("user1"); // Access user1 โ moves to end cache.put("user4", "Diya"); // Capacity exceeded โ user2 evicted (LRU) System.out.println(cache); // {user3=Kishore, user1=Aarav, user4=Diya} // user2 was evicted because it was least recently used! } }
๐ผ Interview Problem 2: Top K Frequent Elements
Given an array [1,1,1,2,2,3] and k=2, return the 2 most frequent elements. Use HashMap for frequency count + PriorityQueue (min-heap of size k) for top-k selection. Expected: [1, 2].
๐ผ Interview Problem 3: Group Anagrams
Given ["eat","tea","tan","ate","nat","bat"], group anagrams together. Use HashMap<String, List<String>> where key = sorted characters. Expected: [[eat,tea,ate], [tan,nat], [bat]].
MCQ Assessment Bank โ 30 Questions (Bloom's Mapped)
Remember / Identify (Q1โQ5)
Which interface is the root of the Collection hierarchy in Java?
- Collection
- Iterable
- List
- Object
Which Collection class uses a doubly-linked list internally?
- ArrayList
- HashSet
- LinkedList
- TreeSet
What is the default initial capacity of a HashMap in Java?
- 8
- 16
- 32
- 10
Which Map implementation maintains keys in sorted order?
- HashMap
- LinkedHashMap
- TreeMap
- Hashtable
PriorityQueue in Java implements which data structure by default?
- Max-heap
- Min-heap
- Binary Search Tree
- Stack
Understand / Explain (Q6โQ10)
Why does HashSet not allow duplicate elements?
- It uses an array that checks every element linearly
- It internally uses a HashMap where elements are stored as keys, and keys must be unique
- It throws an exception when duplicates are added
- It uses a TreeMap for uniqueness checks
What happens when a HashMap bucket's linked list exceeds 8 nodes (Java 8+)?
- The HashMap throws an OverflowException
- The linked list converts to a Red-Black Tree for O(log n) search
- The HashMap doubles its capacity
- The extra nodes are discarded
Why is ArrayList faster than LinkedList for random access (get by index)?
- ArrayList uses hashing
- ArrayList stores elements in contiguous memory, allowing direct index calculation
- LinkedList doesn't support indexing
- ArrayList is synchronized
get(i) directly accesses elementData[i] in O(1). LinkedList must traverse node-by-node from head, making it O(n).What is the difference between Comparable and Comparator?
- Comparable is faster than Comparator
- Comparable defines natural ordering inside the class; Comparator defines custom ordering externally
- Comparator can only sort in ascending order
- Comparable is in java.util; Comparator is in java.lang
Why does modifying a collection inside a for-each loop throw ConcurrentModificationException?
- The JVM doesn't support concurrent operations
- The for-each loop uses an Iterator internally, and structural modifications invalidate the Iterator's state
- The collection becomes read-only during iteration
- for-each loops don't support remove operations
Apply (Q11โQ15)
What is the output of this code?ArrayList<String> list = new ArrayList<>(Arrays.asList("A","B","C")); list.add(1,"X"); System.out.println(list);
- [A, B, C, X]
- [X, A, B, C]
- [A, X, B, C]
- Compilation error
What is the output?HashSet<Integer> set = new HashSet<>(); set.add(10); set.add(20); set.add(10); System.out.println(set.size());
- 3
- 2
- 1
- Compilation error
What does Collections.unmodifiableList(list) return?
- A new sorted list
- A read-only wrapper that throws UnsupportedOperationException on modification
- A synchronized version of the list
- A copy of the list
What is the output?TreeSet<Integer> ts = new TreeSet<>(); ts.add(30); ts.add(10); ts.add(20); System.out.println(ts);
- [30, 10, 20]
- [10, 20, 30]
- [20, 10, 30]
- Exception at runtime
What is the output?HashMap<String,Integer> map = new HashMap<>(); map.put("A",1); map.put("B",2); map.put("A",3); System.out.println(map.get("A"));
- 1
- 3
- null
- Compilation error
Analyze (Q16โQ20)
For an application that needs to frequently check if an element exists in a large dataset (1 million items), which collection is most efficient?
- ArrayList
- LinkedList
- HashSet
- TreeSet
An IRCTC system needs a queue where passengers are served by booking time, but senior citizens get priority. Which collection is best?
- ArrayDeque
- LinkedList
- PriorityQueue with custom Comparator
- ArrayList
A developer stores Student objects in a HashSet but finds duplicates appearing. What is the most likely cause?
- HashSet has a bug
- The Student class has not overridden hashCode() and equals()
- HashSet doesn't check for duplicates
- The JVM version is too old
Which is true about the load factor of a HashMap?
- Higher load factor = more memory, fewer collisions
- Lower load factor = more memory, fewer collisions
- Load factor doesn't affect performance
- Default load factor is 1.0
In what scenario would LinkedList outperform ArrayList?
- Random access by index in a list of 10,000 elements
- Frequent insertions and deletions at the beginning of the list
- Sorting the list using Collections.sort()
- Iterating through all elements sequentially
Evaluate (Q21โQ25)
A Flipkart engineer needs to display recently viewed products in the order they were viewed, with no duplicates. Which collection is best?
- ArrayList
- HashSet
- LinkedHashSet
- TreeSet
Which statement about Java's legacy collections is correct?
- Vector and Hashtable should be used in modern code for thread safety
- Stack should be replaced with ArrayDeque for LIFO operations
- Hashtable is faster than HashMap because it's synchronized
- Vector is preferred over ArrayList for single-threaded applications
For building an autocomplete feature (like Google search suggestions), which collection would you recommend?
- HashMap
- TreeMap
- ArrayList
- HashSet
A system processes 10 million records and needs to find the top 100 highest-valued items. Which approach is most memory-efficient?
- Sort entire list with Collections.sort() and take first 100
- Use a PriorityQueue (min-heap) of size 100
- Store all in TreeSet and iterate
- Use HashMap and scan all values
Which is NOT a valid way to make a HashMap thread-safe?
- Collections.synchronizedMap(hashMap)
- ConcurrentHashMap
- Using synchronized blocks around HashMap operations
- Setting the load factor to 0
Create (Q26โQ30)
To implement an LRU (Least Recently Used) Cache with O(1) get and put, which combination is ideal?
- ArrayList + HashMap
- LinkedHashMap with accessOrder=true
- TreeMap + LinkedList
- HashSet + ArrayDeque
You need to design a Flipkart product search that returns results sorted by price within each category. Which collection combination is best?
- HashMap<String, ArrayList<Product>>
- TreeMap<String, TreeSet<Product>> with Comparator
- LinkedHashMap<String, HashSet<Product>>
- ArrayList<Product> with Collections.sort()
Which code correctly removes all elements less than 40 from an ArrayList during iteration?
for(int x:list) if(x<40) list.remove(x);list.removeIf(x -> x < 40);for(int i=0;i<list.size();i++) list.remove(list.get(i));list.forEach(x -> list.remove(x));
To implement a frequency counter that also maintains insertion order of first occurrences, which Map should you use?
- HashMap
- TreeMap
- LinkedHashMap
- Hashtable
Which design best implements a task scheduler where the highest-priority task runs first, with O(log n) insertion and O(log n) removal?
- ArrayList sorted after every insertion
- TreeSet with custom Comparator
- PriorityQueue with custom Comparator
- LinkedList with insertion sort
Short Answer Questions (8)
Q1. What is the difference between Collection and Collections in Java?
Answer: Collection (singular) is a root interface in java.util that represents a group of objects (extended by List, Set, Queue). Collections (plural) is a utility class in java.util that provides static helper methods like sort(), reverse(), shuffle(), max(), min(), unmodifiableList(). Analogy: Collection is the blueprint of a library; Collections is the librarian who organises books.
Q2. Why doesn't Map extend the Collection interface?
Answer: Collection stores single elements (Collection<E>), while Map stores key-value pairs (Map<K,V>). Their fundamental contracts are different โ Collection has add(E), Map has put(K,V). Forcing Map to extend Collection would require awkward compromises. However, Map provides keySet(), values(), and entrySet() to expose its contents as Collections.
Q3. What is the load factor in HashMap and why is the default 0.75?
Answer: Load factor = (number of entries / number of buckets). It determines when to resize. Default 0.75 means HashMap resizes when 75% full. This is a balanced trade-off: too low (0.5) = more memory, fewer collisions, faster; too high (1.0) = less memory, more collisions, slower. 0.75 is empirically optimal for most use cases, as recommended by Java documentation.
Q4. Explain fail-fast vs fail-safe iterators with examples.
Answer: Fail-fast iterators (ArrayList, HashMap, HashSet) throw ConcurrentModificationException if the collection is structurally modified during iteration. They use an internal modCount field. Fail-safe iterators (ConcurrentHashMap, CopyOnWriteArrayList) work on a copy/snapshot, so modifications don't affect iteration. Example: new ArrayList<>().iterator() is fail-fast; new ConcurrentHashMap<>().keySet().iterator() is fail-safe.
Q5. How does TreeSet maintain sorted order?
Answer: TreeSet uses a Red-Black Tree (a self-balancing binary search tree) internally. Every insertion triggers tree rebalancing to maintain the BST property (left < parent < right). Elements must implement Comparable or a Comparator must be provided. All operations (add, remove, contains) are O(log n) due to tree height being O(log n).
Q6. What happens internally when you call hashMap.put(key, value)?
Answer: Step 1: Compute hash = key.hashCode(), then spread it: hash ^ (hash >>> 16). Step 2: Find bucket index: index = hash & (capacity - 1). Step 3: If bucket is empty, create a new Node and place it there. Step 4: If bucket is occupied, traverse the linked list/tree using equals(). If matching key found, replace value. If not found, append new Node. Step 5: If list length exceeds 8, treeify. Step 6: If size exceeds threshold (capacity ร loadFactor), resize to 2ร capacity.
Q7. Why should you override both hashCode() and equals() for HashMap keys?
Answer: HashMap uses hashCode() to find the bucket and equals() to find the exact key within the bucket. If only equals() is overridden, two equal objects may have different hashCodes (from Object.hashCode()), landing in different buckets โ so get() won't find the key. Contract: if a.equals(b) is true, then a.hashCode() == b.hashCode() must also be true.
Q8. Compare ArrayDeque with Stack and LinkedList for stack operations.
Answer: ArrayDeque is the recommended replacement for both. vs Stack: Stack extends Vector (synchronized, slow). ArrayDeque has no synchronization overhead and is 3โ4ร faster. vs LinkedList: LinkedList allocates a new node object per element (GC pressure, cache misses). ArrayDeque uses a resizable array (contiguous memory, cache-friendly). Java docs explicitly state: "This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue."
Long Answer Questions (3)
Q1. Explain the internal working of HashMap in Java with a diagram. Cover: hashing, bucket array, collision handling (chaining), treeification, and resizing. [10 marks]
Answer:
(a) Hashing: When put(K, V) is called, HashMap computes the hash of the key: int hash = key.hashCode(); hash = hash ^ (hash >>> 16);. The XOR with the upper 16 bits reduces collision probability by spreading the hash bits.
(b) Bucket Index: The bucket index is calculated as index = hash & (n-1) where n = array length (always a power of 2). This is equivalent to hash % n but faster (bitwise AND).
(c) Storage: The bucket array Node<K,V>[] table starts with 16 slots. Each slot (bucket) is initially null. When an entry is added, a Node object (containing hash, key, value, next pointer) is placed at the computed index.
(d) Collision Handling (Chaining): When two keys hash to the same index, a collision occurs. The new Node is appended to the linked list in that bucket. On get(K), the chain is traversed using equals() to find the matching key.
(e) Treeification (Java 8+): When a bucket's linked list exceeds TREEIFY_THRESHOLD (8 nodes), it's converted to a Red-Black Tree for O(log n) lookup instead of O(n). This prevents worst-case performance when many keys hash to the same bucket.
(f) Resizing: When total entries exceed capacity ร loadFactor (default: 16 ร 0.75 = 12), HashMap doubles the array to 32 and rehashes all entries. This is called rehashing. The new index for each entry may change since hash & (newN-1) uses an additional bit.
Time Complexity: O(1) average for put/get/remove. O(log n) worst case per bucket (treeified). O(n) worst case overall only if resize is triggered.
Q2. Compare List, Set, and Map interfaces in Java with at least 8 differences. Provide real-world examples for each. [10 marks]
Answer:
| # | Parameter | List | Set | Map |
|---|---|---|---|---|
| 1 | Duplicates | โ Allowed | โ Not allowed | Keys: โ, Values: โ |
| 2 | Order | Insertion order maintained | Depends (HashSet: no, TreeSet: sorted, LinkedHashSet: insertion) | Depends on implementation |
| 3 | Null elements | Multiple nulls | 1 null (HashSet), 0 (TreeSet) | 1 null key (HashMap), 0 (TreeMap) |
| 4 | Access by index | โ get(index) | โ No index | โ get(key) |
| 5 | Parent interface | Collection | Collection | NOT Collection (separate) |
| 6 | Storage unit | Single element E | Single element E | Key-Value pair (K, V) |
| 7 | Iterator | Iterator + ListIterator | Iterator only | Iterator via entrySet/keySet |
| 8 | Example class | ArrayList, LinkedList | HashSet, TreeSet | HashMap, TreeMap |
Real-world examples: List = Flipkart shopping cart (ordered items, duplicates allowed โ buy 2 of same). Set = Aadhaar database (each citizen has one unique ID). Map = PhonePe contact-to-UPI mapping (name โ UPI ID, instant lookup).
Q3. Discuss Comparable vs Comparator with complete code examples. When would you use one over the other? [10 marks]
Answer:
Comparable (java.lang.Comparable<T>): Defines the natural ordering of a class by implementing compareTo(T other) inside the class itself. Only ONE ordering per class. Used when the class has an obvious default sort order (e.g., String: alphabetical, Integer: ascending).
Comparator (java.util.Comparator<T>): Defines external, custom orderings without modifying the original class. Implements compare(T o1, T o2). Supports MULTIPLE orderings (sort by name, by age, by salary). Can be passed to Collections.sort(), TreeSet, TreeMap, PriorityQueue.
When to use Comparable: (1) You own the class and want a default order. (2) There's one obvious natural order. (3) Example: Student sorted by rollNo by default.
When to use Comparator: (1) You don't own the class (third-party). (2) Multiple sort orders needed. (3) Lambda expressions make it concise in Java 8+. Example: Sort employees by salary, then by name, then by department โ three different Comparators.
Java 8 shortcuts: Comparator.comparing(Student::getName), Comparator.comparing(Student::getPercentage).reversed(), Comparator.comparing(Student::getName).thenComparing(Student::getAge).
Lab Program 4 โ Managing Multiple Items with ArrayList
๐ฌ Lab 4: ArrayList Operations โ Iteration, Add, Remove, Update
Objective:
Write a Java program to manage a list of items (e.g., grocery items) using ArrayList. Implement: add item, remove item by name, update item by index, display all items, and iterate using all three methods (for loop, for-each, Iterator).
Full Code:
Java /* * Lab 4: Managing Multiple Items with ArrayList * Course: Programming in Java โ Unit 13 * Demonstrates: ArrayList operations โ add, remove, update, iterate */ import java.util.ArrayList; import java.util.Iterator; import java.util.Scanner; public class Lab4_ArrayListManager { static ArrayList<String> items = new ArrayList<>(); static Scanner sc = new Scanner(System.in); public static void main(String[] args) { // Pre-load some items items.add("Rice (5kg)"); items.add("Toor Dal (1kg)"); items.add("Sugar (2kg)"); items.add("Milk (1L)"); items.add("Bread (1 pack)"); int choice; do { System.out.println("\nโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"); System.out.println("โ ๐ GROCERY LIST MANAGER โ"); System.out.println("โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ"); System.out.println("โ 1. Add Item โ"); System.out.println("โ 2. Remove Item by Name โ"); System.out.println("โ 3. Update Item by Position โ"); System.out.println("โ 4. Display All (for loop) โ"); System.out.println("โ 5. Display All (for-each loop) โ"); System.out.println("โ 6. Display All (Iterator) โ"); System.out.println("โ 7. Check if item exists โ"); System.out.println("โ 8. Exit โ"); System.out.println("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"); System.out.print("Enter choice: "); choice = sc.nextInt(); sc.nextLine(); // consume newline switch (choice) { case 1: addItem(); break; case 2: removeItem(); break; case 3: updateItem(); break; case 4: displayWithForLoop(); break; case 5: displayWithForEach(); break; case 6: displayWithIterator(); break; case 7: checkItem(); break; case 8: System.out.println("๐ Goodbye!"); break; default: System.out.println("โ Invalid choice!"); } } while (choice != 8); } // ADD โ O(1) amortized static void addItem() { System.out.print("Enter item name: "); String item = sc.nextLine(); items.add(item); System.out.println("โ '" + item + "' added! Total items: " + items.size()); } // REMOVE by name โ O(n) static void removeItem() { System.out.print("Enter item name to remove: "); String item = sc.nextLine(); if (items.remove(item)) { System.out.println("โ '" + item + "' removed!"); } else { System.out.println("โ Item not found!"); } } // UPDATE by index โ O(1) static void updateItem() { displayWithForLoop(); System.out.print("Enter position to update (1-" + items.size() + "): "); int pos = sc.nextInt(); sc.nextLine(); if (pos >= 1 && pos <= items.size()) { System.out.print("Enter new item name: "); String newItem = sc.nextLine(); String old = items.set(pos - 1, newItem); // set() returns old value System.out.println("โ '" + old + "' updated to '" + newItem + "'"); } else { System.out.println("โ Invalid position!"); } } // ITERATION METHOD 1: Traditional for loop static void displayWithForLoop() { System.out.println("\n--- Grocery List (for loop) ---"); for (int i = 0; i < items.size(); i++) { System.out.println((i + 1) + ". " + items.get(i)); } System.out.println("Total: " + items.size() + " items"); } // ITERATION METHOD 2: Enhanced for-each loop static void displayWithForEach() { System.out.println("\n--- Grocery List (for-each) ---"); int count = 1; for (String item : items) { System.out.println(count++ + ". " + item); } } // ITERATION METHOD 3: Iterator (safe for removal during iteration) static void displayWithIterator() { System.out.println("\n--- Grocery List (Iterator) ---"); Iterator<String> it = items.iterator(); int count = 1; while (it.hasNext()) { System.out.println(count++ + ". " + it.next()); } } // CHECK existence โ O(n) static void checkItem() { System.out.print("Enter item to search: "); String item = sc.nextLine(); if (items.contains(item)) { System.out.println("โ Found at position: " + (items.indexOf(item) + 1)); } else { System.out.println("โ Item not in list."); } } }
Viva Questions (5):
- Q: What is the default initial capacity of ArrayList?
A: 10. When the 11th element is added, ArrayList grows by 50% (new capacity = old ร 1.5). So it becomes 15, then 22, then 33, and so on. - Q: What is the difference between remove(int index) and remove(Object o)?
A:remove(int)removes the element at the specified index (O(n) due to shifting).remove(Object)removes the first occurrence of the specified element using equals() (O(n) for search + shifting). ForArrayList<Integer>, useremove(Integer.valueOf(5))to remove value 5, not index 5. - Q: Why is ArrayList not thread-safe? How do you make it thread-safe?
A: ArrayList has no synchronization on its methods. UseCollections.synchronizedList(new ArrayList<>())orCopyOnWriteArrayList(for read-heavy use) for thread safety. - Q: What happens if you call get(10) on an ArrayList of size 5?
A: It throwsIndexOutOfBoundsExceptionat runtime. Always check index bounds:0 โค index < size(). - Q: Can ArrayList store primitive types like int?
A: No. ArrayList stores objects only. Use wrapper classes:ArrayList<Integer>instead ofArrayList<int>. Java's autoboxing automatically convertsint โ Integerand vice versa.
Industry Spotlight โ A Day in the Life
๐ฉโ๐ป Ananya Krishnan, 29 โ Backend Engineer at Flipkart, Bangalore
Background: B.Tech (CS) from NIT Trichy. Joined Flipkart as SDE-1 after campus placement. Promoted to SDE-2 in 2 years. Works on the Catalog and Inventory microservice โ the system that manages 150 million product listings.
A Typical Day:
9:30 AM โ Morning standup with the Catalog team. Discuss yesterday's production incident: HashMap in the pricing service had excessive collisions due to a bad hashCode() implementation for ProductCategory. Fix deployed overnight.
10:30 AM โ Code review for a junior engineer's PR. They used ArrayList where HashSet would be better for deduplication of seller IDs. Leave feedback: "ArrayList.contains() is O(n), HashSet.contains() is O(1). With 50K sellers, this matters."
11:30 AM โ Design discussion for new feature: "Similar Products" recommendation. Proposes using TreeMap<Double, List<Product>> where key = similarity score (sorted), value = list of products with that score.
1:00 PM โ Lunch at Flipkart's Koramangala campus. Chat with Data Science team about using PriorityQueue for ranking search results.
2:30 PM โ Implementing an LRU cache for product metadata using LinkedHashMap. Cache hit rate improved from 65% to 92%, reducing database calls by 3ร.
4:30 PM โ Write unit tests for the cache. Use ConcurrentHashMap for thread safety since the cache is accessed by 200 concurrent threads during Big Billion Day.
6:00 PM โ Tech talk: "Collections Internals" โ presents HashMap's treeification deep-dive to the engineering team.
| Detail | Info |
|---|---|
| Collections Used Daily | HashMap, ConcurrentHashMap, ArrayList, TreeMap, PriorityQueue, LinkedHashMap (LRU Cache) |
| Entry Salary (SDE-1) | โน15โ22 LPA + ESOPs |
| Mid-Level (SDE-2, 3-5 yrs) | โน25โ40 LPA |
| Senior (SDE-3, 7+ yrs) | โน45โ70 LPA |
| Companies Using Collections Heavily | Flipkart, Amazon, Google, Zomato, Swiggy, PhonePe, Razorpay, Zerodha, CRED |
Earn With It โ Freelance & Income Roadmap
๐ฐ Your Earning Path After This Unit: โน10Kโโน30K/month
Portfolio Piece: Student Result Management System / Inventory Management System โ menu-driven, uses ArrayList, HashMap, TreeMap, PriorityQueue. Host on GitHub.
Gig Ideas:
โข Data processing CLI tools for small businesses (CSV โ filtered/sorted reports) โ โน5,000โโน12,000
โข Inventory management desktop apps for kirana stores โ โน8,000โโน20,000
โข Student/employee management systems for coaching centres โ โน5,000โโน15,000
โข Custom data filtering/sorting tools for data entry companies โ โน3,000โโน8,000
| Platform | Best For | Typical Rate |
|---|---|---|
| Internshala | Java intern projects, campus gigs | โน5,000โโน15,000/project |
| Fiverr | Quick Java tools, data processing scripts | $20โ$100/gig (โน1,600โโน8,000) |
| Upwork | Longer Java backend projects | $20โ$50/hour |
| Direct outreach to startups needing Java devs | โน10,000โโน30,000/project | |
| GitHub Portfolio | Showcasing projects for placements | Priceless for landing โน6โ15 LPA jobs |
Chapter Summary
๐ Key Takeaways โ Unit 13: Collections Framework
- Collection Hierarchy: Iterable โ Collection โ List (ordered, duplicates) / Set (unique) / Queue (FIFO). Map is separate (key-value).
- ArrayList = dynamic array, O(1) random access, best for 90% of use cases. Default choice.
- LinkedList = doubly-linked nodes, O(1) insert/delete at known positions, implements Deque.
- HashSet = backed by HashMap, O(1) operations, no duplicates, no order.
- TreeSet = Red-Black Tree, O(log n), sorted order, no null.
- HashMap = array of buckets + linked list/tree, O(1) avg, 16 initial capacity, 0.75 load factor, treeifies at 8.
- TreeMap = sorted by key, O(log n), great for range queries.
- LinkedHashMap = insertion/access order, O(1), perfect for LRU Cache.
- PriorityQueue = min-heap, O(log n) insert/remove, priority-based processing.
- Iterator = safe removal during iteration. Always use Iterator.remove(), never list.remove() inside for-each.
- Comparable = natural order (inside class). Comparator = custom order (external, multiple).
- Override both hashCode() AND equals() when using custom objects as HashMap keys or HashSet elements.
๐ฆ Code Tweet โ Unit 13 in 280 Characters
Java Collections in 1 tweet:
ArrayListโO(1) read, HashMapโO(1) lookup,
TreeMapโsorted keys, HashSetโno dupes,
PriorityQueueโmin-heap, Iteratorโsafe remove,
Comparableโnatural, Comparatorโcustom.
Override hashCode()+equals() or regret it. ๐ฅ #Java
Checkpoint โ Self-Assessment
| Topic | Skill Level | Portfolio Piece | Interview Ready? |
|---|---|---|---|
| Collection Hierarchy | Conceptual | โ | โ Yes โ can draw hierarchy from memory |
| ArrayList Operations | Hands-on (Lab 4) | Grocery List Manager | โ Yes โ add/remove/update/iterate |
| HashMap Internals | Deep Conceptual + Code | FlipkartCatalog | โ Yes โ hashing, buckets, treeification |
| HashSet / TreeSet | Conceptual + Code | VoterBooth Example | โ Yes โ uniqueness, sorting |
| PriorityQueue | Conceptual + Code | Flash Deal Countdown | โ Yes โ min-heap, custom Comparator |
| TreeMap / LinkedHashMap | Conceptual + Code | Sorted Student Marks | โ Yes โ sorted keys, LRU cache |
| Iterator / ListIterator | Hands-on | Safe Removal Example | โ Yes โ ConcurrentModificationException |
| Comparable vs Comparator | Conceptual + Code | StudentResultSystem | โ Yes โ natural vs custom ordering |
| IRCTC Waitlist System | Full Project | IRCTCWaitlist | โ Yes โ Queue + HashMap + ArrayList |
| LRU Cache | Interview-Level | LRUCache | โ Yes โ LinkedHashMap access-order |
โ Unit 13 complete. MCQs: 30. Lab 4 covered. Ready for Unit 14!
[QR: Link to EduArtha video tutorial โ Java Collections Framework]