0% found this document useful (0 votes)
2 views31 pages

Java Collections Complete Handbook

The document is a comprehensive reference guide on Java Collections and Strings, detailing various data structures such as ArrayList, LinkedList, String, StringBuilder, HashMap, and HashSet, along with their methods and usage examples. It includes practical usage scenarios, common mistakes, and interview angles for each data structure. Additionally, it covers Java 8 features like sorting and streams, as well as a quick cheat-sheet for time complexities.

Uploaded by

mandalpritam756
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views31 pages

Java Collections Complete Handbook

The document is a comprehensive reference guide on Java Collections and Strings, detailing various data structures such as ArrayList, LinkedList, String, StringBuilder, HashMap, and HashSet, along with their methods and usage examples. It includes practical usage scenarios, common mistakes, and interview angles for each data structure. Additionally, it covers Java 8 features like sorting and streams, as well as a quick cheat-sheet for time complexities.

Uploaded by

mandalpritam756
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA COLLECTIONS & STRING • COMPLETE REFERENCE

JAVA DATA STRUCTURES


Built-in Methods
Handbook
ArrayList • LinkedList • String • StringBuilder •
HashMap • HashSet • Queue • Stack • Java 8
Collections API

ALL METHODS EXPLAINED USAGE EXAMPLES

MOST USED ★ MARKED

JAVA 8 SORT / REVERSE / COMPARATOR

Compiled for Pritam • Java Developer Reference


CONTENTS

1. ArrayList — Complete Method Guide 01

2. LinkedList — Complete Method Guide 02

3. String — Complete Method Guide 03

4. StringBuilder — Complete Method Guide 04

5. HashMap — Complete Method Guide 05

6. HashSet — Complete Method Guide 06

7. Queue (+ ArrayDeque, PriorityQueue) 07

8. Stack 08

9. Java 8 — [Link], reverse, Comparator, Streams 09

10. Bonus: Iterator & Fail-Fast Behavior 10

11. Common Coding Patterns (HashMap+PQ+Deque) 11

12. Quick Cheat-Sheet — Time Complexities 12


01 ArrayList
[Link]<E>

ArrayList ek resizable array hai ([Link] package) — jab tumhe elements


ka order maintain karna ho aur index se fast access chahiye, tab ArrayList
use karte hai. Internally ye ek dynamic array hai jo full hone pe apne aap
size double kar leta hai.

METHOD POPULAR WHAT IT DOES

add(element) ★ List ke end me element add karta hai. O(1)


amortized.

add(index, element) Specific index pe element insert karta hai, baaki


elements shift ho jate hai. O(n).

get(index) ★ Given index ka element return karta hai. O(1) —


ArrayList ki sabse badi strength.

set(index, element) ★ Given index ka value replace karta hai, purana


value return karta hai.

remove(index) ★ Index se element remove karta hai (int


overload).

remove(Object o) Object ko dhundh ke first occurrence remove


karta hai (Object overload — careful with
Integer!).

size() ★ List me total elements ki count return karta hai.

isEmpty() ★ List khali hai ya nahi — boolean return karta hai.

contains(element) ★ Element list me hai ya nahi check karta hai. O(n).

indexOf(element) Element ka first index return karta hai, nahi mila


to -1.

clear() List ke saare elements remove kar deta hai.

addAll(collection) Ek doosri collection ke saare elements add kar


deta hai.

sort(comparator) ★ List ko given comparator ke hisab se sort karta


hai (List interface, Java 8+).

toArray() ArrayList ko Object[] array me convert karta hai.

subList(from, to) List ka ek portion (view) return karta hai.

forEach(consumer) Har element pe ek action perform karta hai (Java


8 lambda ke saath).

iterator() List ko traverse karne ke liye Iterator return


karta hai (safe removal ke liye).
01 ArrayList — Practical Usage
[Link]<E>

Usage Example

// Declaration
List<Integer> list = new ArrayList<>();

[Link](10);
[Link](20);
[Link](30);
[Link](1, 15); // [10, 15, 20, 30]

[Link]([Link](2)); // 20
[Link](0, 100); // [100, 15, 20, 30]
[Link]([Link](15)); // removes value 15, not index 15!
[Link](0); // removes index 0

for (int x : list) [Link](x); // enhanced for-loop


[Link](x -> [Link](x)); // Java 8 style

Common Mistake: [Link](1) index 1 remove karega, lekin


[Link]([Link](1)) VALUE 1 dhundh ke remove karega. Integer
autoboxing confusion interview me favourite trap question hai!

Common Interview Angles

1. ArrayList vs LinkedList vs Array — kab kaunsa use kare?


2. remove(int) vs remove(Object) ka difference.
3. ArrayList internally kaise resize hota hai (capacity doubling)?
02 LinkedList
[Link]<E>

LinkedList ek doubly-linked list implementation hai jo List aur Deque dono


interfaces implement karta hai. Insert/delete beginning ya middle me fast
hai (O(1) agar node reference pata ho), lekin random access slow hai (O(n))
kyuki index se seedha jump nahi kar sakte.

METHOD POPULAR WHAT IT DOES

add(element) ★ End me element add karta hai.

addFirst(element) ★ List ke start me element add karta hai. O(1).

addLast(element) ★ List ke end me element add karta hai. O(1).

removeFirst() ★ Pehla element remove karke return karta hai.

removeLast() ★ Aakhri element remove karke return karta hai.

getFirst() ★ Pehla element dekhta hai (remove nahi karta).

getLast() ★ Aakhri element dekhta hai (remove nahi karta).

peek() Queue ki tarah — front element dekhta hai, null


agar empty.

poll() Front element remove karke return karta hai, null


agar empty (exception nahi throw karta).

push(element) Stack ki tarah — front me element daalta hai.

pop() Stack ki tarah — front se element nikalta hai.

contains(element) Element hai ya nahi check karta hai. O(n).

size() ★ Total elements count karta hai.

get(index) Index se element access karta hai — O(n),


ArrayList jitna fast nahi.
02 LinkedList — Practical Usage
[Link]<E>

Usage Example

LinkedList<String> ll = new LinkedList<>();


[Link]("B");
[Link]("A");
[Link]("C"); // [A, B, C]

[Link]([Link]()); // A
[Link]([Link]()); // C
[Link](); // [B, C]

// as a Queue
[Link]("D"); // add at end
String front = [Link](); // remove from front

// as a Stack
[Link]("X"); // add at front
String top = [Link](); // remove from front

ArrayList vs LinkedList kab use kare: Agar zyada random access (get/set by
index) chahiye → ArrayList. Agar zyada insertion/deletion at ends ya middle
chahiye (Queue/Deque jaisa use-case) → LinkedList.

Common Interview Angles

1. LinkedList ko Queue aur Stack dono ki tarah kyu use kar sakte hai?
2. Doubly vs Singly linked list ka trade-off.
3. get(index) LinkedList me O(n) kyu hai jabki ArrayList me O(1)?
03 String
[Link] (IMMUTABLE)

String Java me immutable hai — ek baar create hone ke baad uska value
change nahi hota, koi bhi 'modifying' method actually ek NAYA String object
return karta hai. Interview me ye concept bahut pucha jata hai.

METHOD POPULAR WHAT IT DOES

length() ★ String ki total character count


return karta hai.

charAt(index) ★ Given index pe character return


karta hai.

substring(start) ★ Start index se end tak ka substring


return karta hai.

substring(start, end) ★ Start (inclusive) se end (exclusive)


tak ka substring.

indexOf(str) ★ Substring ka first index return


karta hai, nahi mila to -1.

lastIndexOf(str) Substring ka last index return


karta hai.

contains(str) ★ String me substring hai ya nahi


check karta hai.

equals(str) ★ Content-wise compare karta hai


(== se use mat karo!).

equalsIgnoreCase(str) Case-insensitive comparison karta


hai.

compareTo(str) Lexicographic (dictionary order)


comparison karta hai, int return
karta hai.

toUpperCase() / toLowerCase() ★ Case convert karta hai.

trim() / strip() ★ Leading/trailing whitespace


remove karta hai (strip() Unicode-
aware hai, Java 11+).

split(regex) ★ Given delimiter/regex pe string


split karke String[] return karta
hai.

replace(old, new) ★ Saare occurrences replace karta


hai.

toCharArray() ★ String ko char[] array me convert


karta hai.

isEmpty() ★ Length 0 hai ya nahi check karta


hai.

isBlank() Sirf whitespace hai ya empty hai


check karta hai (Java 11+).

startsWith(str) / endsWith(str) Prefix/suffix check karta hai.

valueOf(x) Kisi bhi type (int, char[], boolean)


ko String me convert karta hai.
join(delimiter, elements) Multiple strings ko delimiter se
joda hai (static method, Java 8+).

format(template, args) printf-style formatted string


banata hai.

repeat(n) String ko n baar repeat karta hai


(Java 11+).
03 String — Practical Usage
[Link] (IMMUTABLE)

Usage Example

String s = "Hello World";

[Link]([Link]()); // 11
[Link]([Link](1)); // 'e'
[Link]([Link](6)); // "World"
[Link]([Link](0, 5)); // "Hello"
[Link]([Link]()); // "HELLO WORLD"
[Link]([Link]("World", "Java"));// "Hello Java"

String[] parts = "a,b,c".split(","); // ["a", "b", "c"]


String joined = [Link]("-", "a", "b"); // "a-b"

// Immutability example
String a = "cat";
[Link]("erpillar"); // return value ignored -> a is STILL "cat"
a = [Link]("erpillar"); // now a = "caterpillar"

// == vs equals()
String x = new String("test");
String y = new String("test");
[Link](x == y); // false (different objects)
[Link]([Link](y)); // true (same content)

== vs equals(): == reference/memory address compare karta hai, equals()


content compare karta hai. String comparison me HAMESHA equals() use karo,
warna bugs aayenge.

Common Interview Angles

1. String immutable kyu hai (String Pool, security, thread-safety)?


2. String, StringBuilder, StringBuffer teeno me difference.
3. new String("x") aur "x" literal me kya fark hai (String Pool)?
04 StringBuilder
[Link] (MUTABLE)

StringBuilder mutable hai — jab bahut saare string


concatenations/modifications karne ho (jaise loop me), tab String ki jagah
StringBuilder use karo. Har String concatenation (+) naya object banata hai
jo expensive hai; StringBuilder same object modify karta hai.

METHOD POPULAR WHAT IT DOES

append(x) ★ End me value add karta hai (String, int,


char, sabkuch overload hai). Returns same
object (chaining).

insert(index, x) ★ Given index pe value insert karta hai.

delete(start, end) Range ke characters delete karta hai.

deleteCharAt(index) Ek specific character delete karta hai.

reverse() ★ Poore StringBuilder ko reverse kar deta


hai. O(n).

replace(start, end, str) Range ko naye string se replace karta hai.

charAt(index) Given index ka character return karta hai.

setCharAt(index, ch) Given index ka character change karta hai.

length() ★ Current length return karta hai.

toString() ★ StringBuilder ko immutable String me


convert karta hai.

indexOf(str) Substring ka index dhundta hai.

setLength(n) Length ko force set karta hai (truncate ya


pad with null chars).
04 StringBuilder — Practical Usage
[Link] (MUTABLE)

Usage Example

StringBuilder sb = new StringBuilder();


[Link]("Hello");
[Link](" ").append("World"); // method chaining
[Link](5, ","); // "Hello, World"
[Link](sb); // Hello, World

[Link]();
[Link](sb); // dlroW ,olleH

// Common pattern: building string in a loop


StringBuilder result = new StringBuilder();
for (int i = 1; i <= 5; i++) {
[Link](i).append(",");
}
String finalStr = [Link](); // "1,2,3,4,5,"

// Check Palindrome using StringBuilder


String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();
[Link]([Link](reversed)); // true

Performance: Loop me String += karna O(n²) hai kyuki har baar naya object
banta hai. [Link]() O(1) amortized hai. Bade strings build karte
waqt hamesha StringBuilder use karo.

Common Interview Angles

1. StringBuilder vs StringBuffer — thread safety ka fark.


2. Palindrome check [Link]() se kaise karte hai.
3. StringBuilder mutable kyu hai jabki String immutable?
05 HashMap
[Link]<K,V>

HashMap key-value pairs store karta hai ([Link]). Average case


me get/put O(1) hai (hashing ki wajah se). Order guaranteed nahi hota —
agar insertion order chahiye to LinkedHashMap, sorted order chahiye to
TreeMap use karo.

METHOD POPULAR WHAT IT DOES

put(key, value) ★ Key-value pair add/update karta hai.

get(key) ★ Key ka value return karta hai, nahi mila


to null.

getOrDefault(key, default) ★ Value return karta hai, ya nahi mila to


given default value. Frequency-
counting me bahut useful!

containsKey(key) ★ Key exist karta hai ya nahi check karta


hai.

containsValue(value) Value exist karta hai ya nahi check


karta hai (O(n)).

remove(key) ★ Key-value pair remove karta hai.

keySet() ★ Saari keys ka Set return karta hai


(iterate karne ke liye).

values() Saari values ka Collection return karta


hai.

entrySet() ★ Key-value dono ek saath iterate karne


ke liye Set<[Link]> return karta
hai — sabse efficient iteration.

size() ★ Total pairs ki count.

isEmpty() Map khali hai ya nahi.

putIfAbsent(key, value) ★ Sirf tab add karta hai jab key already
exist na kare.

merge(key, value, function) Existing value ke saath given function


apply karke merge karta hai —
frequency map banane ka modern
tareeka.

compute(key, function) Key ki value ko function apply karke


update karta hai.

forEach((k,v) -> ...) Har entry pe action perform karta hai


(Java 8 lambda).

clear() Saare entries remove kar deta hai.


05 HashMap — Practical Usage
[Link]<K,V>

Usage Example

Map<String, Integer> map = new HashMap<>();


[Link]("apple", 3);
[Link]("banana", 5);
[Link]("apple", 10); // overwrites -> apple = 10

[Link]([Link]("apple")); // 10
[Link]([Link]("mango", 0)); // 0 (not present)

// Frequency count pattern (VERY common in interviews)


String str = "banana";
Map<Character, Integer> freq = new HashMap<>();
for (char c : [Link]()) {
[Link](c, [Link](c, 0) + 1);
// or the Java 8 way:
// [Link](c, 1, Integer::sum);
}

// Iterating - the efficient way


for ([Link]<Character, Integer> entry : [Link]()) {
[Link]([Link]() + " -> " + [Link]());
}

keySet() vs entrySet(): Agar sirf keys chahiye to keySet() use karo. Agar key
AUR value dono chahiye, entrySet() use karo — ye 2x faster hai kyuki
keySet()+get(key) do baar lookup karta hai, entrySet() ek hi baar me deta hai.

Common Interview Angles

1. HashMap internally kaise kaam karta hai (hashing, buckets, collision


handling)?
2. HashMap vs TreeMap vs LinkedHashMap.
3. HashMap thread-safe nahi hota — ConcurrentHashMap kab use kare?
06 HashSet
[Link]<E>

HashSet unique elements ka collection hai (duplicates allowed nahi),


internally HashMap use karta hai. Add/remove/contains average O(1) hai.
Order guaranteed nahi — insertion order chahiye to LinkedHashSet, sorted
chahiye to TreeSet.

METHOD POPULAR WHAT IT DOES

add(element) ★ Element add karta hai, agar already hai to


false return karega (add nahi hoga).

remove(element) ★ Element remove karta hai.

contains(element) ★ Element hai ya nahi check karta hai. O(1)


average — ArrayList ke O(n) se bahut fast.

size() ★ Total unique elements ki count.

isEmpty() Set khali hai ya nahi.

clear() Saare elements remove kar deta hai.

addAll(collection) ★ Doosre collection ke saare elements add karta


hai (duplicates automatically skip ho jate hai).

retainAll(collection) ★ Sirf wahi elements rakhta hai jo dono


collections me common hai — INTERSECTION
nikalne ka tareeka.

removeAll(collection) ★ Given collection ke elements remove karta hai


— DIFFERENCE nikalne ka tareeka.

iterator() Set ko traverse karne ke liye.


06 HashSet — Practical Usage
[Link]<E>

Usage Example

Set<Integer> set = new HashSet<>();


[Link](1);
[Link](2);
[Link](2); // ignored, already present
[Link]([Link]()); // 2

// Remove duplicates from an array - classic use case


int[] arr = {1, 2, 2, 3, 3, 3, 4};
Set<Integer> unique = new HashSet<>();
for (int x : arr) [Link](x);
[Link](unique); // [1, 2, 3, 4]

// Set operations - Union, Intersection, Difference


Set<Integer> a = new HashSet<>([Link](1, 2, 3, 4));
Set<Integer> b = new HashSet<>([Link](3, 4, 5, 6));

Set<Integer> union = new HashSet<>(a);


[Link](b); // [1,2,3,4,5,6]

Set<Integer> intersection = new HashSet<>(a);


[Link](b); // [3,4]

Set<Integer> difference = new HashSet<>(a);


[Link](b); // [1,2]

Interview favourite: 'Find duplicates in array' ya 'check contains fast' jaisa koi
bhi problem ho, HashSet ka O(1) contains() ArrayList ke O(n) contains() se kaafi
behtar hai.

Common Interview Angles

1. HashSet duplicates ko kaise detect karta hai (hashCode + equals)?


2. HashSet vs TreeSet vs LinkedHashSet.
3. Custom object HashSet me daalne se pehle equals()/hashCode() override
karna kyu zaroori hai?
07 Queue / Deque / PriorityQueue
[Link], ARRAYDEQUE, PRIORITYQUEUE

Queue ek interface hai jo FIFO (First-In-First-Out) order follow karta hai.


Common implementations: LinkedList (basic queue), ArrayDeque (fast
double-ended queue, LinkedList se better performance), aur
PriorityQueue (elements priority/sorted order me nikalte hai, heap-based).

METHOD POPULAR WHAT IT DOES

offer(element) ★ Queue me element add karta hai (end me).


Preferred over add().

poll() ★ Front element remove karke return karta hai, null


agar empty.

peek() ★ Front element dekhta hai (remove nahi karta), null


agar empty.

add(element) offer() jaisa hi, lekin fail hone pe exception throw


karta hai.

remove() poll() jaisa hi, lekin fail hone pe exception throw


karta hai.

element() peek() jaisa hi, lekin fail hone pe exception throw


karta hai.

isEmpty() ★ Queue khali hai ya nahi.

size() Total elements ki count.

PriorityQueue (Min-Heap by default)

WHAT IT
METHOD POPULAR
DOES

offer(element) ★ Element add


karta hai, heap
property
maintain hoti
hai. O(log n).

poll() ★ Sabse chota (ya


comparator ke
hisab se top
priority)
element nikalta
hai. O(log n).

peek() ★ Top element


dekhta hai bina
remove kiye.
O(1).

new PriorityQueue<>([Link]()) ★ Max-Heap


banane ka
tareeka —
comparator
reverse kar do.
Queue / Deque / PriorityQueue —
07
Practical Usage
[Link], ARRAYDEQUE, PRIORITYQUEUE

Usage Example

// Basic Queue with LinkedList


Queue<Integer> q = new LinkedList<>();
[Link](1);
[Link](2);
[Link](3);
[Link]([Link]()); // 1 (FIFO)
[Link]([Link]()); // 2

// ArrayDeque - faster than LinkedList for queue/stack use


Deque<Integer> deque = new ArrayDeque<>();
[Link](1);
[Link](2);

// PriorityQueue - Min Heap (default: smallest element first)


PriorityQueue<Integer> minHeap = new PriorityQueue<>();
[Link](5);
[Link](1);
[Link](3);
[Link]([Link]()); // 1 (smallest)

// Max Heap
PriorityQueue<Integer> maxHeap = new PriorityQueue<>([Link]());
[Link](5);
[Link](1);
[Link](3);
[Link]([Link]()); // 5 (largest)

// PriorityQueue with custom Comparator (e.g. for pairs)


PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);

ArrayDeque vs LinkedList: Queue/Stack ke liye ArrayDeque LinkedList se fast


hota hai (better cache locality, no node overhead). Java docs khud recommend
karte hai ArrayDeque use karne ki jab tak LinkedList-specific feature na chahiye.

Common Interview Angles

1. PriorityQueue internally Min-Heap kaise implement karta hai?


2. offer() vs add(), poll() vs remove() — exception behavior ka fark.
3. Top-K elements problem PriorityQueue se kaise solve karte hai?
08 Stack
[Link] / ARRAYDEQUE AS STACK

Stack LIFO (Last-In-First-Out) order follow karta hai. Java ka legacy Stack
class (Vector-based, synchronized, slow) available hai, lekin modern Java
me ArrayDeque ko Stack ki tarah use karna recommended hai (faster,
non-synchronized).

METHOD POPULAR WHAT IT DOES

push(element) ★ Top pe element daalta hai.

pop() ★ Top se element nikal ke return karta hai, empty


hone pe exception.

peek() ★ Top element dekhta hai bina remove kiye, empty


hone pe exception.

isEmpty() ★ Stack khali hai ya nahi.

size() Total elements ki count.

search(element) Element top se kitni distance pe hai return karta


hai (1-indexed), nahi mila to -1.
08 Stack — Practical Usage
[Link] / ARRAYDEQUE AS STACK

Usage Example

// Legacy way (works, but not recommended for new code)


Stack<Integer> stack = new Stack<>();
[Link](1);
[Link](2);
[Link](3);
[Link]([Link]()); // 3
[Link]([Link]()); // 2

// Recommended modern way: ArrayDeque as Stack


Deque<Integer> stack2 = new ArrayDeque<>();
[Link](1);
[Link](2);
[Link]([Link]()); // 2

// Classic use-case: Balanced Parentheses check


public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : [Link]()) {
if (c == '(' || c == '{' || c == '[') {
[Link](c);
} else {
if ([Link]()) return false;
char top = [Link]();
if (c == ')' && top != '(') return false;
if (c == '}' && top != '{') return false;
if (c == ']' && top != '[') return false;
}
}
return [Link]();
}

Interview me Stack kab yaad aaye: Balanced Parentheses, Next Greater


Element, Undo functionality, Expression evaluation, Backtracking (DFS), aur
Recursion ko iterative banane ke liye — ye sab classic Stack use-cases hai.

Common Interview Angles

1. Stack class synchronized/slow kyu hai, ArrayDeque better option kyu hai?
2. Recursion internally call stack use karta hai — explain.
3. Next Greater Element problem Stack se kaise solve karte hai (O(n) trick)?
Java 8 — [Link]() &
09
reverse()
[Link]

Java 8 ne Collections framework me kaafi powerful additions diye —


Collections utility class ke static methods, Comparator ke default/static
methods, aur poora naya Stream API. Ye sab TCS Digital/Advanced rounds
aur real-world Java development dono me heavily use hote hai.

Collections Utility Class ([Link])

METHOD POPULAR WHAT IT DOES

[Link](list) ★ List ko natural order


(ascending) me sort karta
hai. O(n log n).

[Link](list, comparator) ★ Custom order me sort


karta hai.

[Link](list) ★ List ke elements ka order


reverse kar deta hai (in-
place).

[Link](collection) ★ Sabse bada element


return karta hai.

[Link](collection) ★ Sabse chota element


return karta hai.

[Link](list) List ke elements ko


randomly shuffle karta
hai.

[Link](collection, obj) Given object collection me


kitni baar aata hai count
karta hai.

[Link](list) List ka ek read-only


(immutable) view return
karta hai.

[Link]() Ek immutable empty list


return karta hai.

[Link](list, i, j) List ke do indices ke


elements swap karta hai.

[Link](list, key) Sorted list me binary


search karta hai. O(log n).

// [Link] + reverse
List<Integer> nums = new ArrayList<>([Link](5, 2, 8, 1));
[Link](nums); // [1, 2, 5, 8]
[Link](nums); // [8, 5, 2, 1]

[Link](nums, [Link]()); // descending directly


Java 8 — Comparator (Custom
09
Sorting)
[Link]

Comparator & Comparable (Custom Sorting)

METHOD POPULAR WHAT IT DOES

[Link](keyExtractor) ★ Given field/key ke basis pe


comparator banata hai.

.reversed() ★ Existing comparator ka order


reverse kar deta hai.

.thenComparing(keyExtractor) ★ Multi-level sorting — pehle field


se tie hone pe doosre field se
sort.

[Link](comparator) ★ List interface ka apna sort


method (Java 8+),
[Link]() jaisa hi.

Usage Example — Sorting Custom Objects

// Comparator - sorting a list of custom objects


class Student {
String name; int marks;
Student(String n, int m) { name = n; marks = m; }
}

List<Student> students = new ArrayList<>();


[Link](new Student("Amit", 85));
[Link](new Student("Riya", 92));

// Sort by marks ascending


[Link]([Link](s -> [Link]));

// Sort by marks descending


[Link]([Link]((Student s) -> [Link]).reversed());

// Multi-level sort: by marks desc, then name asc


[Link](
[Link]((Student s) -> [Link]).reversed()
.thenComparing(s -> [Link])
);

Multi-level sorting: thenComparing() chain karke tumhe SQL ke 'ORDER BY


col1, col2' jaisa behavior milta hai — ye bahut common interview/real-world
requirement hai.
09 Java 8 — Stream API
[Link]

Stream API Basics ([Link])

METHOD POPULAR WHAT IT DOES

[Link]() ★ Collection ko Stream me convert


karta hai (processing pipeline start).

.filter(condition) ★ Given condition satisfy karne wale


elements hi rakhta hai.

.map(function) ★ Har element ko transform karta hai


(jaise String -> Integer).

.sorted() Stream ko sort karta hai.

.collect([Link]()) ★ Stream ko wapas List me collect


karta hai.

.forEach(action) ★ Har element pe action perform


karta hai.

.reduce(identity, accumulator) Saare elements ko combine karke


ek single result banata hai (jaise
sum).

.count() Stream me total elements ki count.

.anyMatch(condition) Koi bhi ek element condition satisfy


karta hai to true.

Usage Example

List<Integer> nums = [Link](1, 2, 3, 4, 5, 6, 7, 8);

// Filter even numbers, square them, collect into a list


List<Integer> result = [Link]()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect([Link]());
// result = [4, 16, 36, 64]

// Sum using reduce


int sum = [Link]().reduce(0, Integer::sum);

// Sum using Collectors


int sum2 = [Link]().mapToInt(Integer::intValue).sum();

// Sorting with streams


List<Integer> sorted = [Link]()
.sorted([Link]())
.collect([Link]());

TCS Digital/Advanced round tip: [Link]() + custom Comparator


questions bahut common hai (jaise 'sort list of employees by salary'). Stream API
ka basic filter-map-collect pattern bhi aajkal poocha jata hai.
Common Interview Angles

1. Stream vs Collection — laziness aur pipeline concept.


2. map() vs filter() ka difference ek line me.
3. Stream sirf ek baar consume ho sakta hai — kyu (reusability issue)?
Bonus: Iterator &amp; Fail-Fast
10
Behavior
[Link]

Iterator collections ko safely traverse (aur remove) karne ka standard


tareeka hai. Fail-Fast iterators (ArrayList, HashMap ke default) concurrent
modification detect hote hi ConcurrentModificationException throw kar dete
hai.

METHOD POPULAR WHAT IT DOES

hasNext() ★ Aur elements bache hai ya nahi check karta hai.

next() ★ Agla element return karta hai aur pointer aage


badhata hai.

remove() ★ Iterator ke current element ko SAFELY collection se


remove karta hai (loop ke andar hi).

ListIterator List ke liye bidirectional iterator — hasPrevious(),


previous(), set() bhi deta hai.

Usage Example

List<Integer> list = new ArrayList<>([Link](1, 2, 3, 4, 5));

// WRONG way - throws ConcurrentModificationException


for (Integer x : list) {
if (x == 3) [Link](x); // ERROR at runtime!
}

// CORRECT way - using [Link]()


Iterator<Integer> it = [Link]();
while ([Link]()) {
int x = [Link]();
if (x == 3) {
[Link](); // safe removal during iteration
}
}
[Link](list); // [1, 2, 4, 5]

Interview classic: 'Loop ke andar list se element remove karne pe exception


kyu aata hai?' — Answer: fail-fast iterator modCount track karta hai; agar
collection loop ke beech me directly modify hua ([Link]()), to next iteration
pe exception throw hota hai. Solution: [Link]() use karo.
11 Common Coding Patterns
HASHMAP + PRIORITYQUEUE + DEQUE COMBOS

Ye woh combinations hai jo TCS/product-company coding rounds me baar


baar use hote hai — ek hi problem me do-teen data structures milke kaam
karte hai.

Pattern 1: Frequency Map + Max/Min (HashMap)

Character/element frequency count karke sabse zyada/kam repeat hone


wala element dhundna — HashMap ka sabse common use-case.

Map<Character, Integer> freq = new HashMap<>();


for (char c : [Link]())
[Link](c, 1, Integer::sum);

char mostFrequent = ' ';


int max = 0;
for ([Link]<Character, Integer> e : [Link]()) {
if ([Link]() > max) { max = [Link](); mostFrequent = [Link](); }
}

Pattern 2: Top-K Elements (HashMap + PriorityQueue)

Frequency HashMap banao, fir usse ek min-heap PriorityQueue me daalo


size K rakhte hue — O(n log k) me Top-K nikal jata hai.

PriorityQueue<[Link]<Character,Integer>> pq =
new PriorityQueue<>((a, b) -> [Link]() - [Link]());

for ([Link]<Character,Integer> e : [Link]()) {


[Link](e);
if ([Link]() > k) [Link](); // remove smallest, keep top-k
}

Pattern 3: Sliding Window (Deque / ArrayDeque)

Fixed-size window ke max/min nikalne ke liye Deque use karo — front se


purane out-of-window elements nikalo, back se chote elements nikal ke
naya daalo.

Deque<Integer> dq = new ArrayDeque<>(); // stores indices


for (int i = 0; i < [Link]; i++) {
while (![Link]() && nums[[Link]()] < nums[i])
[Link]();
[Link](i);
if ([Link]() <= i - k) [Link]();
if (i >= k - 1) [Link](nums[[Link]()]); // window max
}
12 Quick Cheat-Sheet (1/2)
TIME COMPLEXITY REFERENCE

Quick revision ke liye — sabhi data structures ke average-case time


complexities ek jagah.

WHAT IT
METHOD POPULAR
DOES

ArrayList: get/set ★ O(1)

ArrayList: add/remove at end ★ O(1)


amortized

ArrayList: add/remove at index O(n)

LinkedList: addFirst/addLast/removeFirst/removeLast ★ O(1)

LinkedList: get(index) O(n)

HashMap: get/put/remove/containsKey ★ O(1)


average

HashSet: add/remove/contains ★ O(1)


average
13 Quick Cheat-Sheet (2/2)
TIME COMPLEXITY REFERENCE

Baaki data structures ke time complexities.

METHOD POPULAR WHAT IT DOES

TreeMap/TreeSet: all operations O(log n)

Queue (ArrayDeque): offer/poll/peek ★ O(1)

PriorityQueue: offer/poll ★ O(log n)

PriorityQueue: peek O(1)

Stack: push/pop/peek ★ O(1)

[Link]() / [Link]() ★ O(n log n)

StringBuilder: append ★ O(1) amortized

String: concatenation (+) in a loop O(n) per operation -> O(n²)


overall
Happy Coding, Pritam!

Ye handbook tumhare TCS interviews, coding rounds aur


daily Java development — teeno me kaam ayega. ★
marked methods sabse zyada use hote hai, unko sabse
pehle practice karo.

You might also like