From ArrayList vs LinkedList to HashMap internals, TreeMap, ConcurrentHashMap, Streams & LeetCode patterns — one tutorial you can read, learn, understand, and explain in an interview.
How to use: For every collection — Theory → Analogy → When to use → Internal Working → Time Complexity → Complete Runnable Code → Real-Time Use → LeetCode → Interview Line.
| Question | If YES → Use |
|---|---|
| Do you need key → value lookup? | Map — HashMap / TreeMap |
| Do you need duplicates? Order matters? | List — ArrayList / LinkedList |
| Do you need unique values only? | Set — HashSet / TreeSet |
| Do you need FIFO / Priority processing? | Queue — ArrayDeque / PriorityQueue |
Arrays are fixed, hard to use, and have no ready methods. Collections are dynamic, rich, and interview-ready.
| Array Problem | Collection Solution |
|---|---|
Fixed size — new int[10] cannot grow | ArrayList grows automatically (1.5x) |
| No methods — search, sort, remove manually | Ready methods: add, remove, contains, sort |
| Only primitives + objects, no generics | Generics: List<String> — type-safe |
| No Set / Map / Queue built-in | Full framework: List, Set, Map, Queue, Deque |
import java.util.*;
public class ArrayVsCollectionComplete {
public static void main(String[] args) {
// ARRAY: fixed, manual work
String[] arr = new String[2];
arr[0] = "A"; arr[1] = "B";
// arr[2] = "C"; // ArrayIndexOutOfBoundsException — cannot grow!
System.out.println("Array length fixed: " + arr.length);
// COLLECTION: dynamic, easy
List<String> list = new ArrayList<>();
list.add("A"); list.add("B"); list.add("C"); list.add("D"); // grows automatically
System.out.println("List: " + list + " size=" + list.size());
System.out.println("Contains C? " + list.contains("C"));
list.remove("B");
System.out.println("After remove B: " + list);
Collections.sort(list);
System.out.println("Sorted: " + list);
// Generics: List<String> cannot add Integer — compile error, type-safe
// list.add(123); // COMPILE ERROR — good!
}
}
A set of interfaces + classes + algorithms in java.util to store and process groups of objects. Interfaces = contract (what to do). Classes = implementation (how to do). Algorithms = utility methods (sort, search, shuffle).
Collection (interface) — root for List, Set, Queue
├── List — Ordered, allows duplicates, index-based
│ ├── ArrayList, LinkedList, Vector, Stack, CopyOnWriteArrayList
├── Set — No duplicates
│ ├── HashSet, LinkedHashSet, TreeSet, EnumSet
├── Queue — FIFO / Priority
│ ├── PriorityQueue, ArrayDeque, LinkedList (also Queue)
└── Deque — Double-ended queue (add/remove both ends)
└── ArrayDeque, LinkedList
Map (interface) — NOT part of Collection, separate root
├── HashMap, LinkedHashMap, TreeMap, Hashtable, ConcurrentHashMap, WeakHashMap
| Interface | Order? | Duplicates? | Example |
|---|---|---|---|
| List | Yes, insertion order | Yes | Shopping cart, to-do list |
| Set | HashSet: No. LinkedHashSet: Yes. TreeSet: Sorted | No | Unique emails, unique tags |
| Queue | FIFO / Priority | Yes | Print queue, task queue |
| Deque | Both ends | Yes | Undo/Redo, browser history |
| Map | HashMap: No. LinkedHashMap: Yes. TreeMap: Sorted keys | Keys: No, Values: Yes | UserId → User, Word → Count |
import java.util.*;
public class HierarchyComplete {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("A", "A", "B")); // duplicates OK
Set<String> set = new HashSet<>(List.of("A", "A", "B")); // duplicates removed
Queue<String> queue = new ArrayDeque<>(List.of("First", "Second"));
Deque<String> deque = new ArrayDeque<>(List.of("Middle"));
Map<String, Integer> map = new HashMap<>(Map.of("A", 1, "B", 2));
System.out.println("List (duplicates): " + list); // [A, A, B]
System.out.println("Set (unique): " + set); // [A, B]
System.out.println("Queue poll (FIFO): " + queue.poll()); // First
deque.addFirst("Front"); deque.addLast("Back");
System.out.println("Deque: " + deque); // [Front, Middle, Back]
System.out.println("Map get A: " + map.get("A")); // 1
// Common methods: size(), isEmpty(), contains(), clear(), iterator()
}
}
Most asked List question: “ArrayList vs LinkedList — which to use?” The answer is not “ArrayList is always better.” It depends on operation.
Internal: Dynamic array (Object[] elementData). Default capacity 10. When full, grows to 1.5x (old + old/2). New array created, old elements copied.
Time Complexity:
| Operation | ArrayList | Why? |
|---|---|---|
| get(i) | O(1) | Direct index: arr[i] |
| add (end) | O(1) amortized | Append, grow rarely |
| add (middle) | O(n) | Shift elements right |
| remove (middle) | O(n) | Shift elements left |
| contains / search | O(n) | Linear scan |
Internal: Doubly Linked List. Each node has prev + data + next. No array, no resizing. Implements both List and Deque.
| Operation | LinkedList | Why? |
|---|---|---|
| get(i) | O(n) | Walk from head/tail to i |
| addFirst / addLast | O(1) | Just change pointers |
| add (middle) | O(n) | Walk to position, then O(1) link |
| removeFirst / Last | O(1) | Pointer change |
import java.util.*;
public class ListPerformanceComplete {
public static void main(String[] args) {
int N = 100000;
List<Integer> arrayList = new ArrayList<>();
List<Integer> linkedList = new LinkedList<>();
for (int i = 0; i < N; i++) { arrayList.add(i); linkedList.add(i); }
// 1) Random access — ArrayList wins big
long start = System.nanoTime();
for (int i = 0; i < 10000; i++) arrayList.get(N / 2);
System.out.println("ArrayList get(50000) x10000: " + (System.nanoTime() - start) / 1_000_000 + " ms");
start = System.nanoTime();
for (int i = 0; i < 10000; i++) linkedList.get(N / 2);
System.out.println("LinkedList get(50000) x10000: " + (System.nanoTime() - start) / 1_000_000 + " ms");
// 2) Add at beginning — LinkedList wins
start = System.nanoTime();
for (int i = 0; i < 1000; i++) arrayList.add(0, i); // shifts 100k elements each time!
System.out.println("ArrayList add(0) x1000: " + (System.nanoTime() - start) / 1_000_000 + " ms");
start = System.nanoTime();
for (int i = 0; i < 1000; i++) linkedList.add(0, i); // just pointer change
System.out.println("LinkedList add(0) x1000: " + (System.nanoTime() - start) / 1_000_000 + " ms");
}
}
| Thread-Safe? | Growth | When to Use | |
|---|---|---|---|
| ArrayList | No | 1.5x | Single thread, 95% cases |
| Vector | Yes (synchronized, slow) | 2x | Legacy — DO NOT use, use ArrayList + sync or CopyOnWrite |
| CopyOnWriteArrayList | Yes (lock-free read) | Copy whole array on write | Read-heavy, write-rare: listeners, config |
import java.util.concurrent.*;
public class CopyOnWriteComplete {
public static void main(String[] args) throws Exception {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(List.of("A", "B"));
// Reader iterates — no lock, no ConcurrentModificationException
for (String s : list) { System.out.println("Reading: " + s); list.add("C"); } // safe!
System.out.println("After: " + list);
System.out.println("Rule: Write copies whole array — expensive if writes are frequent. Use only for read-heavy.");
}
}
Problem: Given [2,7,11,15], target 9, return indices [0,1].
Easy: Two loops O(n²). Optimized: One pass with HashMap O(n) — for each number, check if target - num already in map.
import java.util.*;
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>(); // value → index
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (map.containsKey(need)) return new int[]{map.get(need), i};
map.put(nums[i], i);
}
return new int[]{-1, -1};
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new TwoSum().twoSum(new int[]{2,7,11,15}, 9))); // [0,1]
}
}Set = No duplicates. But which Set? Depends on whether you need order, sorting, or just uniqueness.
| Set | Internal | Order | Null? | get / add | Use When |
|---|---|---|---|---|---|
| HashSet | HashMap (value = dummy) | No order | 1 null OK | O(1) | Just uniqueness, fastest |
| LinkedHashSet | LinkedHashMap | Insertion order | 1 null OK | O(1) | Uniqueness + insertion order |
| TreeSet | TreeMap (Red-Black Tree) | Sorted order | No null | O(log n) | Uniqueness + sorted |
| EnumSet | Bit vector | Enum order | No null | O(1) | Set of enum values, fastest |
HashSet.add(x) = map.put(x, PRESENT) where PRESENT is a dummy object. That is why HashSet has same O(1) and same hashCode rules as HashMap.import java.util.*;
public class SetComplete {
public static void main(String[] args) {
Set<String> hashSet = new HashSet<>();
Set<String> linkedSet = new LinkedHashSet<>();
Set<String> treeSet = new TreeSet<>();
String[] words = {"Banana", "Apple", "Mango", "Apple", "Banana"};
for (String w : words) { hashSet.add(w); linkedSet.add(w); treeSet.add(w); }
System.out.println("HashSet (no order): " + hashSet); // [Apple, Banana, Mango] any order
System.out.println("LinkedHashSet (insertion): " + linkedSet); // [Banana, Apple, Mango]
System.out.println("TreeSet (sorted): " + treeSet); // [Apple, Banana, Mango]
// Useful Set operations
Set<Integer> a = new HashSet<>(Set.of(1,2,3,4));
Set<Integer> b = new HashSet<>(Set.of(3,4,5,6));
Set<Integer> union = new HashSet<>(a); union.addAll(b); // {1,2,3,4,5,6}
Set<Integer> inter = new HashSet<>(a); inter.retainAll(b); // {3,4}
Set<Integer> diff = new HashSet<>(a); diff.removeAll(b); // {1,2}
System.out.println("Union=" + union + " Intersection=" + inter + " Diff=" + diff);
}
}
Problem: Given array, return true if any value appears twice.
import java.util.*;
public class ContainsDuplicate {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int n : nums) {
if (!seen.add(n)) return true; // add returns false if already present
// seen.add() is O(1) — better than contains() + add() (2 lookups)
}
return false;
}
public static void main(String[] args) {
System.out.println(new ContainsDuplicate().containsDuplicate(new int[]{1,2,3,1})); // true
}
}
Interview tip: Use add() return value — it already tells you if duplicate. Do not do contains() then add() (2 hashes).
Problem: Given [100,4,200,1,3,2], longest consecutive = [1,2,3,4] length 4. Must be O(n).
import java.util.*;
public class LongestConsecutive {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int n : nums) set.add(n);
int longest = 0;
for (int n : set) {
if (!set.contains(n - 1)) { // only start counting from sequence start
int curr = n, len = 1;
while (set.contains(curr + 1)) { curr++; len++; }
longest = Math.max(longest, len);
}
}
return longest;
}
public static void main(String[] args) {
System.out.println(new LongestConsecutive().longestConsecutive(new int[]{100,4,200,1,3,2})); // 4
}
}
Why O(n)? Each number is visited at most twice — once as start check, once in while loop. Without the !contains(n-1) check, it would be O(n²).
HashMap is the most asked topic in Java interviews. If you can explain its internals, you can crack any Map question.
key.hashCode() → spread function (h ^ (h >>> 16)) to mix high bits.index = hash & (capacity - 1). Capacity is power of 2 (16, 32, 64) so & works like % but faster.size > capacity * loadFactor (0.75), double capacity, rehash all entries. Default: 16 → 32 → 64.HashMap Visual (capacity 16):
Bucket 0: null
Bucket 1: [KeyA → Val] → [KeyB → Val] // collision: A and B same index
Bucket 2: [KeyC → Val]
...
Bucket 15: null
// get(KeyB): hash → index 1 → walk chain → equals() match → return Val
roll % 16. If two students get same classroom, they sit in a row (chain). If row gets too long (>8), teacher makes a sorted tree to find students faster. If school fills 75%, build a bigger school (resize) and reassign classrooms.import java.util.*;
public class HashMapComplete {
// Custom key with BAD hashCode — all keys go to same bucket → O(n)
static class BadKey {
String name;
BadKey(String n) { name = n; }
public int hashCode() { return 1; } // BAD: all same bucket
public boolean equals(Object o) { return o instanceof BadKey && ((BadKey)o).name.equals(name); }
public String toString() { return name; }
}
// Custom key with GOOD hashCode — distributed
static class GoodKey {
String name;
GoodKey(String n) { name = n; }
public int hashCode() { return Objects.hash(name); } // GOOD: distributed
public boolean equals(Object o) { return o instanceof GoodKey && ((GoodKey)o).name.equals(name); }
public String toString() { return name; }
}
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 1); map.put("B", 2); map.put("A", 10); // duplicate key overwrites
System.out.println("Map: " + map); // {A=10, B=2} — key A updated, not duplicated
System.out.println("Get A: " + map.get("A"));
System.out.println("GetOrDefault X: " + map.getOrDefault("X", -1));
System.out.println("Contains Key B? " + map.containsKey("B"));
// computeIfAbsent — only one thread loads from DB (cache pattern)
Map<String, String> cache = new HashMap<>();
String val = cache.computeIfAbsent("user:101", k -> "DB-User-" + k);
System.out.println("Cache: " + val);
// merge — word count in one line
Map<String, Integer> wordCount = new HashMap<>();
for (String w : "apple banana apple mango apple".split(" ")) wordCount.merge(w, 1, Integer::sum);
System.out.println("WordCount: " + wordCount); // {apple=3, banana=1, mango=1}
}
}
| Map | Order | Null Key? | Thread-Safe? | get/put | Use When |
|---|---|---|---|---|---|
| HashMap | No | 1 null key OK | No | O(1) | General, fastest, single thread |
| LinkedHashMap | Insertion / Access order | 1 null OK | No | O(1) | LRU Cache, insertion order |
| TreeMap | Sorted by key | No null key | No | O(log n) | Sorted keys, range queries |
| Hashtable | No | No null | Yes (slow) | O(1) | Legacy — DO NOT use |
| ConcurrentHashMap | No | No null | Yes (fast) | O(1) | Multi-threaded, production |
| WeakHashMap | No | 1 null OK | No | O(1) | Cache where key can be GC'd |
import java.util.*;
public class LRUComplete {
static class LRUCache<K,V> extends LinkedHashMap<K,V> {
private final int capacity;
LRUCache(int cap) { super(cap, 0.75f, true); capacity = cap; } // true = access-order
protected boolean removeEldestEntry(Map.Entry<K,V> e) { return size() > capacity; }
}
public static void main(String[] args) {
LRUCache<Integer, String> cache = new LRUCache<>(3);
cache.put(1, "A"); cache.put(2, "B"); cache.put(3, "C");
System.out.println(cache); // {1=A, 2=B, 3=C}
cache.get(1); // 1 becomes most recent
cache.put(4, "D"); // 2 is LRU, evicted
System.out.println(cache); // {3=C, 1=A, 4=D} — 2 evicted
}
}
import java.util.*;
public class TreeMapComplete {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(10, "Ten"); map.put(5, "Five"); map.put(20, "Twenty"); map.put(15, "Fifteen");
System.out.println("Sorted: " + map); // {5, 10, 15, 20}
System.out.println("First: " + map.firstKey() + " Last: " + map.lastKey());
System.out.println("Floor 12 (≤12): " + map.floorKey(12)); // 10
System.out.println("Ceiling 12 (≥12): " + map.ceilingKey(12)); // 15
System.out.println("SubMap 10-20: " + map.subMap(10, 20)); // {10, 15}
System.out.println("HeadMap <15: " + map.headMap(15)); // {5, 10}
// Real-time: Leaderboard, time-series (timestamp → event), price ranges
}
}
Problem: Group ["eat","tea","tan","ate","nat","bat"] → [["eat","tea","ate"],["tan","nat"],["bat"]].
import java.util.*;
public class GroupAnagrams {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] chars = s.toCharArray();
Arrays.sort(chars); // sorted chars = key: "aet" for eat/tea/ate
String key = new String(chars);
map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}
return new ArrayList<>(map.values());
}
public static void main(String[] args) {
System.out.println(new GroupAnagrams().groupAnagrams(new String[]{"eat","tea","tan","ate","nat","bat"}));
}
}Problem: Design LRU Cache with get() and put() in O(1). See LRU code above (LinkedHashMap version). Interview twist: “Implement without LinkedHashMap?” → Use HashMap + Doubly Linked List: HashMap for O(1) lookup, DLL for O(1) move-to-head + remove-tail. See Multithreading tutorial Ch 10 for full DLL version.
import java.util.*;
public class TopKFrequent {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> freq = new HashMap<>();
for (int n : nums) freq.merge(n, 1, Integer::sum);
// Min-heap of size k: smallest freq at top, evict when > k
PriorityQueue<Map.Entry<Integer, Integer>> heap =
new PriorityQueue<>(Map.Entry.comparingByValue());
for (var e : freq.entrySet()) { heap.offer(e); if (heap.size() > k) heap.poll(); }
int[] res = new int[k];
for (int i = k - 1; i >= 0; i--) res[i] = heap.poll().getKey();
return res;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new TopKFrequent().topKFrequent(new int[]{1,1,1,2,2,3}, 2))); // [1,2]
}
}Queue = FIFO. Deque = Both ends. PriorityQueue = By priority, not FIFO. Stack = LIFO. Choosing wrong one is a common interview mistake.
| Structure | Order | Best Class | Use When |
|---|---|---|---|
| Queue (FIFO) | First in, first out | ArrayDeque / LinkedList | Task queue, print queue, BFS |
| Deque | Both ends | ArrayDeque | Undo, sliding window, palindrome |
| PriorityQueue | By priority (min-heap) | PriorityQueue | Top K, Dijkstra, scheduling |
| Stack (LIFO) | Last in, first out | ArrayDeque (NOT Stack class) | Undo, expression, DFS, parentheses |
Stack class: It is legacy, synchronized, extends Vector (slow). Use ArrayDeque as Stack: push(), pop(), peek(). Interviewers check this.import java.util.*;
public class QueueDequeComplete {
public static void main(String[] args) {
// QUEUE: FIFO
Queue<String> queue = new ArrayDeque<>();
queue.offer("First"); queue.offer("Second"); queue.offer("Third");
System.out.println("Queue poll: " + queue.poll()); // First
System.out.println("Queue peek: " + queue.peek()); // Second
// DEQUE: both ends
Deque<String> deque = new ArrayDeque<>();
deque.addFirst("Front"); deque.addLast("Back");
System.out.println("Deque: " + deque); // [Front, Back]
System.out.println("Deque pollFirst: " + deque.pollFirst()); // Front
// PRIORITY QUEUE: min-heap, smallest first
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(30); pq.offer(10); pq.offer(20);
System.out.println("PQ poll order: " + pq.poll() + ", " + pq.poll() + ", " + pq.poll()); // 10,20,30
// Max-heap: reverse order
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
maxHeap.offer(10); maxHeap.offer(30); maxHeap.offer(20);
System.out.println("MaxHeap poll: " + maxHeap.poll()); // 30
// STACK via ArrayDeque: LIFO
Deque<String> stack = new ArrayDeque<>();
stack.push("A"); stack.push("B"); stack.push("C");
System.out.println("Stack pop: " + stack.pop()); // C (last in, first out)
System.out.println("Stack peek: " + stack.peek()); // B
}
}
| Operation | Returns special value (safe) | Throws exception |
|---|---|---|
| Add | offer() → false if full | add() → IllegalStateException |
| Remove | poll() → null if empty | remove() → NoSuchElementException |
| Examine | peek() → null if empty | element() → NoSuchElementException |
Interview tip: Always use offer / poll / peek (safe) in production, not add / remove / element (throws).
import java.util.*;
public class ValidParentheses {
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>(); // use Deque as Stack
Map<Character, Character> pairs = Map.of(')', '(', '}', '{', ']', '[');
for (char c : s.toCharArray()) {
if (pairs.containsValue(c)) stack.push(c);
else if (stack.isEmpty() || stack.pop() != pairs.get(c)) return false;
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(new ValidParentheses().isValid("()[]{}")); // true
System.out.println(new ValidParentheses().isValid("(]")); // false
}
}Problem: [1,3,-1,-3,5,3,6,7], k=3 → [3,3,5,5,6,7]. Naive O(n*k) too slow. Deque gives O(n).
import java.util.*;
public class SlidingWindowMax {
public int[] maxSlidingWindow(int[] nums, int k) {
Deque<Integer> deque = new ArrayDeque<>(); // stores indices, decreasing values
int[] res = new int[nums.length - k + 1];
for (int i = 0; i < nums.length; i++) {
// Remove indices out of window
if (!deque.isEmpty() && deque.peekFirst() <= i - k) deque.pollFirst();
// Remove smaller values — they can never be max
while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) deque.pollLast();
deque.offerLast(i);
if (i >= k - 1) res[i - k + 1] = nums[deque.peekFirst()];
}
return res;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new SlidingWindowMax().maxSlidingWindow(new int[]{1,3,-1,-3,5,3,6,7}, 3)));
}
}import java.util.*;
public class KthLargest {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // size k, smallest at top
for (int n : nums) { minHeap.offer(n); if (minHeap.size() > k) minHeap.poll(); }
return minHeap.peek(); // kth largest = smallest in top-k heap
}
public static void main(String[] args) {
System.out.println(new KthLargest().findKthLargest(new int[]{3,2,1,5,6,4}, 2)); // 5
}
}If you get this wrong, HashMap / HashSet will silently fail — duplicate objects, lost entries, wrong contains().
a.equals(b) is true, then a.hashCode() == b.hashCode() MUST be true.a.hashCode() == b.hashCode(), then a.equals(b) MAY be false (collision allowed).equals(), you MUST override hashCode() — and vice versa. If you override only one, HashMap breaks.import java.util.*;
public class EqualsHashCodeBroken {
// WRONG: equals overridden, hashCode NOT overridden — uses Object.hashCode (memory address)
static class UserBroken {
String id;
UserBroken(String id) { this.id = id; }
public boolean equals(Object o) { return o instanceof UserBroken && ((UserBroken)o).id.equals(id); }
// hashCode NOT overridden — BUG!
}
// CORRECT: both overridden, using same fields
static class UserCorrect {
String id;
UserCorrect(String id) { this.id = id; }
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserCorrect)) return false;
return Objects.equals(id, ((UserCorrect)o).id);
}
public int hashCode() { return Objects.hash(id); } // same field as equals
}
public static void main(String[] args) {
// BROKEN: two equal users, different hashCodes → HashMap treats as different keys
Map<UserBroken, String> brokenMap = new HashMap<>();
brokenMap.put(new UserBroken("101"), "Dharmendra");
System.out.println("Broken get (should be Dharmendra): " + brokenMap.get(new UserBroken("101"))); // null — BUG!
// CORRECT: same hashCode → same bucket → equals match → found
Map<UserCorrect, String> correctMap = new HashMap<>();
correctMap.put(new UserCorrect("101"), "Dharmendra");
System.out.println("Correct get: " + correctMap.get(new UserCorrect("101"))); // Dharmendra
Set<UserCorrect> set = new HashSet<>();
set.add(new UserCorrect("101")); set.add(new UserCorrect("101"));
System.out.println("Set size (should be 1): " + set.size());
}
}
id, hashCode must use id only.Objects.equals() and Objects.hash() — null-safe.// BEST: Java Record — equals, hashCode, toString auto-generated, immutable
record UserRecord(String id, String name) {}
// Usage: Map<UserRecord, String> map = new HashMap<>();
// map.put(new UserRecord("101", "Dharmendra"), "Data"); // works correctly, no manual code
| Comparable | Comparator | |
|---|---|---|
| Method | compareTo() | compare() |
| Where? | Inside class itself | Separate class / lambda |
| How many orderings? | One — natural ordering | Many — by name, age, salary, etc. |
| Package | java.lang | java.util |
| Example | String, Integer implement Comparable | Comparator.comparing(User::getAge) |
import java.util.*;
public class SortingComplete {
static class Student implements Comparable<Student> {
String name; int age; int marks;
Student(String n, int a, int m) { name = n; age = a; marks = m; }
// Natural ordering: by marks (ascending)
public int compareTo(Student other) { return Integer.compare(this.marks, other.marks); }
public String toString() { return name + "(" + marks + ")"; }
}
public static void main(String[] args) {
List<Student> list = new ArrayList<>(List.of(
new Student("Asha", 20, 85), new Student("Ravi", 22, 90), new Student("Meena", 19, 75)));
// 1) Natural ordering (Comparable): by marks
Collections.sort(list);
System.out.println("By marks: " + list); // Meena(75), Asha(85), Ravi(90)
// 2) Comparator: by name
list.sort(Comparator.comparing(s -> s.name));
System.out.println("By name: " + list);
// 3) Comparator: by age descending, then by name
list.sort(Comparator.comparingInt((Student s) -> s.age).reversed().thenComparing(s -> s.name));
System.out.println("By age desc: " + list);
// 4) Modern: Stream sorting
List<Student> top = list.stream().sorted(Comparator.comparingInt((Student s) -> s.marks).reversed()).limit(2).toList();
System.out.println("Top 2 by marks: " + top);
// 5) Collections utility: binarySearch (list MUST be sorted)
List<Integer> nums = new ArrayList<>(List.of(10, 20, 30, 40));
System.out.println("binarySearch 30: index " + Collections.binarySearch(nums, 30)); // 2
System.out.println("Max: " + Collections.max(nums) + " Min: " + Collections.min(nums));
Collections.reverse(nums); System.out.println("Reversed: " + nums);
Collections.shuffle(nums); System.out.println("Shuffled: " + nums);
}
}
ClassCastException. HashSet / HashMap do not need sorting.compare(a,b)==0 but !a.equals(b), TreeSet may treat them as duplicates and drop one.| Fail-Fast | Fail-Safe | |
|---|---|---|
| Examples | ArrayList, HashMap, HashSet | ConcurrentHashMap, CopyOnWriteArrayList |
| What happens on modify during iteration? | ConcurrentModificationException | No exception, works on snapshot / weakly consistent |
| How? | modCount check — if modCount changes during iteration, throw | Copy / segment lock — iterator sees old snapshot |
import java.util.*;
import java.util.concurrent.*;
public class FailFastComplete {
public static void main(String[] args) {
// BUG: Fail-Fast — ConcurrentModificationException
List<String> list = new ArrayList<>(List.of("A", "B", "C"));
try {
for (String s : list) { if (s.equals("B")) list.remove(s); } // throws!
} catch (ConcurrentModificationException e) {
System.out.println("Fail-Fast: ConcurrentModificationException as expected");
}
// FIX 1: Iterator.remove() — allowed
List<String> list2 = new ArrayList<>(List.of("A", "B", "C"));
Iterator<String> it = list2.iterator();
while (it.hasNext()) { if (it.next().equals("B")) it.remove(); }
System.out.println("Fix1 Iterator.remove: " + list2); // [A, C]
// FIX 2: removeIf (Java 8+) — cleanest
List<String> list3 = new ArrayList<>(List.of("A", "B", "C"));
list3.removeIf(s -> s.equals("B"));
System.out.println("Fix2 removeIf: " + list3);
// FIX 3: Fail-Safe collection — CopyOnWriteArrayList, no exception
CopyOnWriteArrayList<String> cow = new CopyOnWriteArrayList<>(List.of("A", "B", "C"));
for (String s : cow) { if (s.equals("B")) cow.remove(s); } // no exception, iterates snapshot
System.out.println("Fix3 CopyOnWrite: " + cow);
// ConcurrentHashMap — Fail-Safe, no exception, weakly consistent
ConcurrentHashMap<String, Integer> cmap = new ConcurrentHashMap<>(Map.of("A", 1, "B", 2));
for (var e : cmap.entrySet()) { cmap.put("C", 3); } // no exception
System.out.println("ConcurrentHashMap: " + cmap);
}
}
Old (Java 7): Segmented locks — 16 segments, each with its own lock. Threads writing to different segments do not block each other.
New (Java 8+): CAS + synchronized on bucket (first node). Read is lock-free. Write locks only one bucket, not whole map. That is why it is much faster than Hashtable (which locks whole map).
Key rules: No null key / value (throws NPE). computeIfAbsent is atomic. size() is approximate (not exact) under concurrency — use mappingCount().
import java.util.concurrent.*;
public class ConcurrentMapComplete {
public static void main(String[] args) throws Exception {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// 10 threads increment same key 1000 times — should be 10000
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) map.merge("visits", 1, Integer::sum);
});
threads[i].start();
}
for (Thread t : threads) t.join();
System.out.println("Visits = " + map.get("visits")); // Always 10000, thread-safe
// Hashtable would also be thread-safe but much slower (whole map lock)
}
}
Problem: Filter, map, sort, collect — with loops it is 15 lines. With Streams, 3 lines, readable, parallelizable.
import java.util.*;
import java.util.stream.*;
public class StreamsComplete {
record Student(String name, int marks, String city) {}
public static void main(String[] args) {
List<Student> students = List.of(
new Student("Asha", 90, "Mumbai"), new Student("Ravi", 70, "Delhi"),
new Student("Meena", 95, "Mumbai"), new Student("Arjun", 60, "Delhi"));
// 1) Filter + Map + Collect: names of Mumbai students with marks > 80
List<String> names = students.stream()
.filter(s -> s.city().equals("Mumbai") && s.marks() > 80)
.map(Student::name)
.sorted()
.toList();
System.out.println("Mumbai toppers: " + names); // [Asha, Meena]
// 2) Grouping: city → list of students
Map<String, List<Student>> byCity = students.stream().collect(Collectors.groupingBy(Student::city));
System.out.println("By city: " + byCity);
// 3) Counting / Averaging: average marks per city
Map<String, Double> avgByCity = students.stream()
.collect(Collectors.groupingBy(Student::city, Collectors.averagingInt(Student::marks)));
System.out.println("Avg by city: " + avgByCity);
// 4) Max / Min: topper
students.stream().max(Comparator.comparingInt(Student::marks)).ifPresent(s -> System.out.println("Topper: " + s));
// 5) Parallel stream: for large lists, use parallel() — uses ForkJoinPool
List<Integer> big = IntStream.rangeClosed(1, 1000000).boxed().toList();
long sum = big.parallelStream().mapToLong(Integer::longValue).sum();
System.out.println("Parallel sum: " + sum);
// 6) Common mistake: Stream can be used only once!
Stream<String> stream = Stream.of("A", "B");
stream.forEach(System.out::println);
// stream.forEach(System.out::println); // IllegalStateException — stream already consumed!
System.out.println("Rule: Stream is single-use. Create new stream for each operation.");
}
}
| Real Problem | Collection to Use | Why? |
|---|---|---|
| Word frequency, user visits | HashMap + merge() | O(1) count, one line |
| Unique visitors | HashSet | O(1) duplicate check |
| Leaderboard, sorted scores | TreeSet / TreeMap | Sorted, O(log n) |
| LRU Cache | LinkedHashMap (access-order) | O(1) get/put + eviction |
| Task queue, BFS | ArrayDeque (Queue) | O(1) offer/poll |
| Undo / Redo, parentheses | ArrayDeque (Stack) | O(1) push/pop |
| Top K, scheduling | PriorityQueue (Heap) | O(log n) insert, O(1) peek |
| Sliding window max | ArrayDeque (Monotonic) | O(n) instead of O(n*k) |
| Multi-threaded cache | ConcurrentHashMap | Thread-safe, fast, no whole-map lock |
| Read-heavy listeners | CopyOnWriteArrayList | Lock-free read, no CME |
| Pattern | Collection | LeetCode Examples |
|---|---|---|
| HashMap for O(1) lookup | HashMap | Two Sum (1), Group Anagrams (49), Isomorphic Strings (205) |
| HashSet for duplicate / seen | HashSet | Contains Duplicate (217), Longest Consecutive (128), Happy Number (202) |
| Two Pointers + List | ArrayList / Array | 3Sum (15), Container With Most Water (11), Remove Duplicates (26) |
| Stack for matching / monotonic | ArrayDeque | Valid Parentheses (20), Daily Temperatures (739), Largest Rectangle (84) |
| Heap for Top K | PriorityQueue | Kth Largest (215), Top K Frequent (347), Merge K Sorted Lists (23) |
| Deque for sliding window | ArrayDeque | Sliding Window Max (239), First Negative in Window |
import java.util.*;
public class LongestSubstring {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> lastSeen = new HashMap<>(); // char → last index
int max = 0, start = 0;
for (int end = 0; end < s.length(); end++) {
char c = s.charAt(end);
if (lastSeen.containsKey(c)) start = Math.max(start, lastSeen.get(c) + 1);
lastSeen.put(c, end);
max = Math.max(max, end - start + 1);
}
return max;
}
public static void main(String[] args) {
System.out.println(new LongestSubstring().lengthOfLongestSubstring("abcabcbb")); // 3 (abc)
System.out.println(new LongestSubstring().lengthOfLongestSubstring("bbbbb")); // 1 (b)
}
}
Pattern: Sliding window + HashMap for last seen index. O(n), one pass. This pattern also solves: Minimum Window Substring (76), Longest Repeating Character Replacement (424).
import java.util.*;
public class ThreeSum {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums); // sort first — O(n log n)
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue; // skip duplicate i
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
res.add(List.of(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left+1]) left++;
while (left < right && nums[right] == nums[right-1]) right--;
left++; right--;
} else if (sum < 0) left++; else right--;
}
}
return res;
}
public static void main(String[] args) {
System.out.println(new ThreeSum().threeSum(new int[]{-1,0,1,2,-1,-4})); // [[-1,-1,2],[-1,0,1]]
}
}import java.util.*;
public class MergeKLists {
static class ListNode { int val; ListNode next; ListNode(int v) { val = v; } }
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> heap = new PriorityQueue<>(Comparator.comparingInt(n -> n.val));
for (ListNode n : lists) if (n != null) heap.offer(n);
ListNode dummy = new ListNode(0), curr = dummy;
while (!heap.isEmpty()) {
ListNode smallest = heap.poll();
curr.next = smallest; curr = curr.next;
if (smallest.next != null) heap.offer(smallest.next);
}
return dummy.next;
}
public static void main(String[] args) {
System.out.println("Merge K Lists: Heap always gives smallest head — O(N log K).");
}
}== for String / Integer instead of .equals().equals() without hashCode() — HashMap breaks.ConcurrentModificationException. Use Iterator.remove() or removeIf().Stack class instead of ArrayDeque.Vector / Hashtable instead of ArrayList / HashMap / ConcurrentHashMap.LinkedList.get(i) in loop — O(n²). Use iterator or ArrayList.String + in loop — use StringBuilder.Stream is single-use.| Question | One-Line Answer |
|---|---|
| ArrayList vs LinkedList? | ArrayList: O(1) get, good for random access. LinkedList: O(1) add/remove at ends. |
| HashMap vs TreeMap? | HashMap: O(1), no order. TreeMap: O(log n), sorted. |
| HashSet internal? | HashMap with dummy value. |
| equals + hashCode? | If equals true, hashCode must be equal. Override both together. |
| Fail-Fast vs Fail-Safe? | Fail-Fast throws CME. Fail-Safe uses snapshot / concurrent, no exception. |
| Comparable vs Comparator? | Comparable: natural, inside class. Comparator: custom, outside class. |
| Queue offer vs add? | offer returns false if full. add throws exception. |
| PriorityQueue order? | Min-heap by default. Smallest first. |
| ConcurrentHashMap vs Hashtable? | CHM locks one bucket, fast. Hashtable locks whole map, slow. CHM: no nulls. |
| When to use Deque? | Both ends: sliding window, undo, palindrome, BFS. |
Q: Why is HashMap not thread-safe?
A: Two threads putting at same time can corrupt bucket chain or lose entries during resize. Use ConcurrentHashMap for multi-threaded code.
Q: Can HashMap have null key?
A: Yes, one null key (stored in bucket 0). HashSet can have one null. TreeMap cannot have null key (needs comparison), ConcurrentHashMap cannot have null key/value (throws NPE).
Q: What is load factor 0.75?
A: Trade-off between time and space. Lower load factor = fewer collisions, more memory. Higher = more collisions, less memory. 0.75 is the sweet spot found by research.
Q: ArrayList vs Array?
A: ArrayList is dynamic, has methods, uses generics, but only stores objects (autoboxing for primitives). Array is fixed, faster for primitives, no methods.
Q: What is unmodifiable collection?
A: List.copyOf() or Collections.unmodifiableList() — read-only view. Any add/remove throws UnsupportedOperationException. Use for returning safe copies from APIs.
Need Key → Value? ──YES──► Need sorted keys? ──YES──► TreeMap
│ └──NO──► Need thread-safe? ──YES──► ConcurrentHashMap
│ └──NO──► HashMap (or LinkedHashMap for order)
└──NO
Need unique only? ──YES──► Need sorted? ──YES──► TreeSet
│ └──NO──► Need insertion order? ──YES──► LinkedHashSet
│ └──NO──► HashSet
└──NO
Need FIFO / Priority? ──YES──► Need priority? ──YES──► PriorityQueue
│ └──NO──► ArrayDeque as Queue
└──NO
Need LIFO (Stack)? ──YES──► ArrayDeque as Stack
└──NO──► Need index access? ──YES──► ArrayList
└──NO──► LinkedList / ArrayDeque