Cosmic Module
J
Qubits of DPK
March 14, 2026
Core Java
Layman Explanation
Arrays are fixed-size boxes. Collections are expandable bags — they grow and shrink dynamically. Stream API is a conveyor belt that processes data in that bag without changing the original.
Collection Hierarchy
javascript
QUBITS OF DPK
ArrayList
java
QUBITS OF DPK
ArrayList vs Array
javascript
QUBITS OF DPK
Set
java
QUBITS OF DPK
Map
java
QUBITS OF DPK
Comparator vs Comparable
Comparable (natural ordering)
java
QUBITS OF DPK
Comparator (custom ordering)
java
QUBITS OF DPK
Stream API
Process collections in a functional, pipeline style without modifying the original.
java
QUBITS OF DPK
Collections Cheat Sheet
️ All Traps
java
QUBITS OF DPK
Interview Answer (SDE-2)
"The Java Collections Framework provides dynamic data structures. List maintains order with duplicates (ArrayList for access, LinkedList for insertion). Set prevents duplicates (HashSet fastest, TreeSet sorted, LinkedHashSet ordered). Map stores key-value pairs (HashMap general use, TreeMap sorted, LinkedHashMap ordered). Stream API enables declarative data processing pipelines — lazy evaluation, intermediate ops (filter/map/sorted) and terminal ops (collect/reduce/forEach). Comparator for external sorting, Comparable for natural ordering. In production, prefer ConcurrentHashMap over HashMap for thread safety."
Interview Questions & MAANG-Level Answers
Q1. What is the difference between ArrayList and LinkedList?
ArrayList: backed by a dynamic array — O(1) random access by index, O(n) insert/delete at middle (shifting), cache-friendly, less memory overhead. LinkedList: doubly linked list — O(n) random access (traverse from head), O(1) insert/delete at head/tail if reference known, more memory (each node stores prev/next pointers). Use ArrayList for most cases (random access, iteration). Use LinkedList only for frequent insertions at ends (queue/deque operations).
Q2. What is the difference between HashSet, LinkedHashSet, and TreeSet?
HashSet: no ordering guarantee, O(1) add/remove/contains — fastest, uses HashMap internally. LinkedHashSet: maintains insertion order, O(1) operations, uses LinkedHashMap internally — use when order matters. TreeSet: sorted natural order (or custom Comparator), O(log n) operations, uses TreeMap internally — use when sorted iteration needed. All three reject duplicates using equals() and hashCode().
Q3. What is the difference between HashMap and Hashtable?
HashMap: not thread-safe, allows one null key and multiple null values, faster. Hashtable: thread-safe (all methods synchronized), no null keys or values, legacy class from Java 1.0. In modern Java, use ConcurrentHashMap instead of Hashtable for thread safety — it's much faster due to segment locking (not whole-table locking). HashMap is preferred for single-threaded code.
Q4. What is Comparable vs Comparator?
Comparable: implemented BY the class itself — defines natural ordering via compareTo(). The class "knows" how to compare itself. Comparator: external comparison logic — passed to sort methods. Allows multiple different orderings without modifying the class:
java
QUBITS OF DPK
Use Comparable for the primary/natural ordering; Comparator for alternate orderings.
Q5. What is lazy evaluation in Streams?
Intermediate Stream operations (filter, map, sorted, distinct) are LAZY — they don't execute until a terminal operation (collect, forEach, reduce, count) is called. This enables optimization: if you filter + limit, Java stops after finding enough elements without processing the rest:
java
QUBITS OF DPK
Short-circuiting operations (findFirst, anyMatch, limit) can terminate the pipeline early. This is why streams can efficiently process infinite data sources.
Q6. What is the difference between map() and flatMap()?
map(): transforms each element to exactly one output — 1-to-1 mapping. stream.map(x -> x * 2) — each element produces one result. flatMap(): transforms each element to zero or more outputs and flattens nested streams — 1-to-many:
java
QUBITS OF DPK
flatMap used for: splitting sentences into words, flattening nested collections, optional chaining.
Q7. Can you reuse a Stream? What happens if you try?
No. A Stream can only be consumed ONCE. After a terminal operation executes, the stream is closed. Trying to use it again throws IllegalStateException: stream has already been operated upon or closed. Always create a new stream from the source: list.stream() creates a fresh stream each time.
Q8. What is ConcurrentModificationException and how to avoid it?
Thrown when you structurally modify a collection while iterating it with a for-each loop or Iterator:
java
QUBITS OF DPK
Fixes: (1) Use Iterator.remove(): it.remove() during iteration. (2) list.removeIf(predicate) — cleanest. (3) Collect items to remove, then remove after loop. (4) Use CopyOnWriteArrayList for concurrent scenarios. The CME check is a fail-fast mechanism using a modCount counter.
Q9. How does HashMap handle hash collisions?
Collision: two keys produce the same bucket index. HashMap uses separate chaining: each bucket is a linked list of entries. On collision, new entry is appended to the list. Java 8 optimization: when a bucket's linked list exceeds 8 nodes, it converts to a Red-Black Tree — improving worst-case from O(n) to O(log n). When entries drop below 6, converts back to linked list.
Q10. What is the internal working of HashMap?
HashMap internally uses an Entry[] table (array of buckets). put(key, value): (1) Compute hash(key) — uses key's hashCode() then spreads bits. (2) Compute index: hash & (capacity-1). (3) If bucket empty, insert new Entry. (4) If bucket has entries, check for duplicate key via equals() — update if found, append if not. get(key): same hash computation — find bucket, traverse chain with equals() to find exact entry. Default capacity 16, load factor 0.75 — resizes (doubles) when 75% full, rehashing all entries.