0% found this document useful (0 votes)
38 views41 pages

Understanding Java Generics and Collections

Generic and Collection Framework in Java

Uploaded by

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

Understanding Java Generics and Collections

Generic and Collection Framework in Java

Uploaded by

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

Generic classes and

methods.
Collection frameworks:
list & map

- By Sai Teja Polisetty


Collections
• Collection Framework =
interfaces + implementations for
working with groups of objects.
• Core interfaces: List, Set,
Queue/Deque (all extend
Collection); Map is separate.
• Benefits: type-safe generics, ready-
made algorithms, consistent APIs.
• PTR: “Lists keep order, Sets keep
uniqueness, Queues handle
workflow, Maps map keys →
values.”

- By polisetty Sai Teja 2


Why Generic?
• Before Generics, Java collections like ArrayList or
HashMap could store any type of object,
everything was treated as an Object. It had some
problems. Without Generic With Generics
• If you added a String to a List, Java didn’t List list = new List<Integer> nums =
remember its type. You had to manually cast it
when retrieving. If the type was wrong, it caused
ArrayList(); new ArrayList<>();
a runtime error. [Link](42);
// raw type Integer n2 =
• With Generics, you can specify the type the [Link]("42"); [Link](0);
collection will hold like ArrayList<String>. Now, Integer n = (Integer)
Java knows what to expect and it checks at [Link](0); // // no cast, type-safe
compile time, not at runtime. ClassCastException at
• “imagine a ‘box’ that can hold anything. runtime
convenient, but risky.”

“with generics, we move the error to compile time (best


place to catch it).”
- By polisetty Sai Teja 3
Class with single type parameter Class with multiple type
parameter
class Test<T> { class Test<T, U>

Generic T obj;
Test(T obj) {
{
T obj1; // An object of type T
U obj2; // An object of type U

class
[Link] = obj;
} Test(T obj1, U obj2)
public T getObject() { return {
[Link]; } this.obj1 = obj1;
} this.obj2 = obj2;
}
• A generic class is like a class Dpoint {
public static void main(String[] public void print()
regular class but uses type args) {
parameters (like <T>). { [Link](obj1);
• It can accept one or more // instance of Integer type [Link](obj2);
Test<Integer> iObj = new }
types, making the class Test<Integer>(15); }
reusable for different data
types. Such classes are [Link]([Link]()); class Dpoint
called parameterized classes. {
// instance of String type public static void main (String[]
Test<String> sObj args)
= new {
Test<String>("GeeksForGeeks"); Test <String, Integer> obj =
new Test<String,
[Link]([Link]()); Integer>("GfG", 15);
}
} - By polisetty Sai Teja [Link](); 4
}
• A generic method is a method that can work with different
data types using a type parameter. It lets you write one
method that works for all types, instead of repeating the
same logic.
• class Geeks {

// A Generic method example


static <T> void genericDisplay(T element)
{
[Link]([Link]().getName()
Generic }
+ " = " + element);

Method public static void main(String[] args)


{
// Calling generic method with Integer argument
genericDisplay(11);

// Calling generic method with String argument


genericDisplay("GeeksForGeeks");

// Calling generic method with double argument


genericDisplay(1.0);
}
}
- By polisetty Sai Teja 5
Bounded type params

• limit which types are allowed.”


• // only numbers
static <T extends Number> double sum(T a,
T b){
return [Link]() + [Link]();
}
// multiple bounds
static <T extends Number &
Comparable<T>> T max2(T a, T b){
- By polisetty Sai Teja
return ([Link](b) >= 0) ? a : 6b;
}
Producer Extends Consumer Super (PECS):

Cat. Definition Diagram


Exten ? extends T means
d “an unknown type that is
T or a subtype of T.”

Inheritance direction
downward
Super ? super T means: “some
unknown type that is T
or a supertype of T.”

Example: ? super Integer


could be:
Integer itself
Number (parent of
Integer)
Object (parent of
everything in Java)
- By polisetty Sai Teja 7
Producer Extends Consumer Super (PECS):

? extends T ? super T
Feature
(Producer) (Consumer)
Some subtype of Some supertype
Meaning
T of T
Safe For Reading (get) Writing (add)
Reading Returns T Returns Object
❌ Not allowed ✅ Can add T
Writing
(except null) values
List<? extends List<? super
Example
Number> Integer>
Basket
Basket producing
Analogy consuming
Apples
Apples

- By polisetty Sai Teja 8


? extends T → Producer Extends ? super T → Consumer Super (you
(you READ) WRITE)
Think: “a basket that produces Ts for Think: “a basket that can consume Ts
me to look at.” I put into it.” Variance with
double total(List<? extends Number> static <T> void copy(List<? super T> dst, wildcards & PECS:
nums) { List<? extends T> src) {
double s = 0; for (T t : src) {
for (Number n : nums) s += [Link](t); // ✅ safe to write T into a ?
[Link](); super T
// ✅ read as Number } • invariance demo:
// [Link](1); // ❌ can't add // T x = [Link](0); List<Number> ln = new
(except null) // ⚠️reading gives only Object (type could ArrayList<>();
return s; be supertype)
} } List<Integer> li = new
ArrayList<>();
// ln = li; // ❌ not allowed
• Why no adds? Because nums • If dst is List<Object> or (invariance)
might actually be a List<Double> List<Number>, it’s safe to add any
at runtime. T (like Integer) to it.
• If we allowed [Link](1), we’d • Rule: With ? super T, you can write
shove an Integer into a Double list. T into it safely, but reads are only
• Rule: With ? extends T, you can guaranteed as Object.
read items as T, but you cannot
add (except null).

- By polisetty Sai Teja 9


PECS : producer extends, Situation Use Why
consumers super
Summing List<? extends You only read
numbers from a Number> values as Number
• If the parameter is a list

source you only read from Filling a list with


integers
List<? super
Integer>
You write Integers
safely.
→ ? extends T
Copy from one list copy(List<? Source produces
• If the parameter is a to another super T> dst, (extends), dest
destination you write to List<? extends
T> src)
consumes (super).

→ ? super T
• If you need to both read Sort with a
comparator
Comparator<?
super T>
A comparator of a
supertype can
and write as the same T → compare Ts.

use a type parameter <T>


Transform with <T> T You both read and
(no wildcard) same in/out type max(List<T>) return T—use a
type param, not
- By polisetty Sai Teja
wildcards. 10
Limitations of Generics
Name Description Snippet
No primitives as type You can’t use int, double, etc. Use // ❌ Test<int> t = new Test<int>();
arguments wrappers. ✅ Test<Integer> t = new Test<>();
// Arrays are reference types, so this is
fine:
✅ List<int[]> frames = new ArrayList<>();
No generic array creation You can’t create arrays of // ❌ List<String>[] a = new
parameterized types or of T. List<String>[10];
// ❌ T[] arr = new T[10];
✅ List<List<String>> a = new
ArrayList<>(); // use lists of lists
// (Raw arrays compiles with warnings—
avoid.)
Can’t use a class’s type static members don’t see the instance class Repo<T> {
parameter in static context type parameter. // ❌ static T cache;
static <U> Repo<U> empty() { return
null; } // ✅ declare your own <U>
}
Wildcards are intentionally ? extends T is (effectively) read-only; ? void sum(List<? extends Number> xs) { /*
restrictive super T is write-only (reads as Object). can read Number, can’t add */ }
void addAll(List<? super Integer> dst)
{ [Link](42); /* reads are Object */ }
No generic exceptions / catches You can’t make class MyEx<T>
- By polisetty extends
Sai Teja // ❌ class Bad<T> extends Exception
11 {}
Exception {} and you can’t catch (T e). // ❌ catch (T e) { ... }
Benefits of
Generics
• Code Reusability
• Type Safety
• Individual type casting not
needed

- By polisetty Sai Teja 12


Without Generics With Generics
// Non-generic page: items are just Objects (or interface FeedItem { String title(); }
FeedItem) record Movie(String title, int minutes) implements FeedItem {}
record PageRaw(List<Object> items, int page, int record Series(String title, int seasons) implements FeedItem {}
totalPages) {}
record Page<T>(List<T> items, int page, int totalPages) {} // T is
class FeedServiceRaw { the item type
PageRaw loadRow(String rowId) {
// could be movies or series... caller has to guess class FeedService {
return new PageRaw([Link](new Movie("Inception", // T is any FeedItem subtype; Class<T> says WHICH subtype we
148)), 1, 1); want
} <T extends FeedItem> Page<T> loadRow(String rowId,
} Class<T> kind) {

🎬 NETFLIX // imagine we fetched JSON and mapped each element to 'kind'


List<T> items = fetchAndMap(rowId, kind); // returns List<T>

— “one
return new Page<>(items, 1, 10);
}

feed, many // stub to illustrate the idea


private <T extends FeedItem> List<T> fetchAndMap(String

item types” rowId, Class<T> kind) {


// Example: if kind == [Link] → build List<Movie>
// If kind == [Link] → build List<Series>
return [Link]();
}
}
How to call: How to call:
var page = new FeedService svc = new FeedService();
FeedServiceRaw().loadRow("continue");
// Ask for movies:
// You must cast -- risky: Page<Movie> movies = [Link]("continue", [Link]);
Movie m = (Movie) [Link]().get(0); // might Movie m = [Link]().get(0); // ✅ already a Movie (no cast)
throw ClassCastException at runtime
// Ask for series:
- By polisetty Sai Teja Page<Series> shows = [Link]("trending", [Link]);
13
Series s = [Link]().get(0); // ✅ already a Series
🔎 GOOGLE — “one search, many result
kinds”
• “How can Google Search return a single results page

Few More that sometimes has Web, Image, Video results—each


with different fields—without losing type safety?”

Use cases 🚗 TESLA — “typed sensors & alerts”

• “How can telemetry code reuse the same pipeline for


temperature, speed, voltage… but reject mixing
types?”

- By polisetty Sai Teja 14


Question Options
1 Generics provide type _____. A) safety B) casting C) reflection D)
serialization
2 Java generics use type ____ at A) erasure B) reification C) templates
runtime. D) metadata
3 Default variance of List<T> is A) invariance B) covariance C)
_____. contravariance D) variance
4 In PECS, a producer uses _____. A) extends B) super C) bounds D)
wildcard
5 In PECS, a consumer uses _____. A) super B) extends C) bounds D)
wildcard
Question Options
6 Wildcard symbol is _____. A) ? B) T C) K D) V 11 The wildcard rule acronym is A) PECS B) SOLID C) DRY D)
_____. MISS
7 Upper bound keyword is _____. A) extends B) super C) implements D) 12 Using a raw type (e.g., List) is A) unsafe B) faster C)
bounds generally _____. immutable D) synchronized
8 Lower bound keyword is _____. A) super B) extends C) below D) lower 13 Primitives as type arguments are A) disallowed B) promoted
_____. C) autoboxed D) nullable
9 A generic method declares type A) return B) class C) package D)
14 new T() in a generic class is A) illegal B) generic C)
parameters before the ____ type. import
_____. cached D) reflective
10 List<?> is effectively ____-only. A) read B) write C) sync D) cast
15 Direct creation of generic arrays A) forbidden B) safe C) static
(T[]) is _____. D) trivial
16 Comparator<? ____ T> in sorting A) super B) extends C) of D)
APIs typically uses _____. for
17 Multiple bounds are joined with A) ampersand B) comma C)
an _____. plus D) pipe
18 The diamond operator enables A) inference B) erasure C)
type _____. boxing D) promotion

Quiz 19
- By polisetty Sai Teja
20
Type parameters cannot be
referenced from a ____ context.
To accept any subtype of
A) static B) dynamic C)
generic D) override
15
A) extends B) super C) over
Question Answer
1 Generics provide type _____. safety (A)

2 Java generics use type ____ at erasure (A)


runtime.
3 Default variance of List<T> is invariance (A)
_____.
4 In PECS, a producer uses _____. extends (A)

5 In PECS, a consumer uses _____. super (A)


Question Answer
6 Wildcard symbol is _____. ? (A)
11 The wildcard rule acronym is A) PECS
_____.
7 Upper bound keyword is _____. A) extends
12 Using a raw type (e.g., List) is A) unsafe
8 Lower bound keyword is _____. A) super generally _____.
13 Primitives as type arguments are A) disallowed
9 A generic method declares type A) return
_____.
parameters before the ____ type.
14 new T() in a generic class is A) illegal
10 List<?> is effectively ____-only. A) read
_____.
15 Direct creation of generic arrays A) forbidden
(T[]) is _____.
16 Comparator<? ____ T> in sorting A) super
APIs typically uses _____.
17 Multiple bounds are joined with A) ampersand
an _____.
18 The diamond operator enables A) inference
type _____.

Answer
19 Type parameters cannot be A) static
referenced from a ____ context.
- By polisetty Sai Teja 16
20 To accept any subtype of A) extends
List
• an ordered collection that allows
duplicates. - Order matters (index
based).
• “Think Spotify playlist—order
matters, the same song can repeat.”
• Example:
List<String> names = new
ArrayList<>();
[Link]("A"); [Link]("B");
[Link]("A"); // duplicates allowed
[Link]([Link](1)); //
"B"

- By polisetty Sai Teja 17


record Track(String id, String title, boolean explicit, int
rating /*1..5*/) {}

Spotify —
Playlist editor class Playlist {
private final List<Track> tracks = ??? ;
(ordering,
duplicates, void add(Track t) { ??? }
allowed
// duplicates

sorting, safe void swap(int i, int j){ ??? } // reorder

removal) void removeExplicit(){ ??? } // safe bulk removal


void sortByRating(){ ??? }

// "Up next" window (first N) -- returns a *view* of the list


List<Track> upNext(int n){
return ??? // view, not a copy
}
}

- By polisetty Sai Teja 18


Implementation Use when Big O (Amortized) Notes

ArrayList general purpose; lots of get O(1), add-end contiguous array; ensureCapacity
reads; append-heavy O(1), insert/remove helps; great default
middle O(n)

LinkedList mostly head/tail ops; lots of get O(n), higher memory; random access
listIterator inserts/removes add/remove ends slow; usually prefer ArrayList or
O(1) ArrayDeque for queues/stacks

CopyOnWriteArrayList many reads, very few get O(1), write O(n) snapshot iterators; great for
writes, iteration must never (copies array) listeners/observers
fail
[Link](.. need a synchronized must synchronized(list) { iterate }
.) wrapper to iterate safely

Unmodifiable ([Link], you want read-only views or of/copyOf throw on mutate &
[Link], copies disallow nulls
[Link])

Quick rules:
•Default: ArrayList.
Implementation •For queue/stack: use ArrayDeque, not LinkedList.
•For read-mostly shared lists: CopyOnWriteArrayList.
- By polisetty Sai Teja 19
Core • List<String> l = new ArrayList<>();

Api's • [Link]("red");
• [Link](0, "blue");
// append
// insert at index
• [Link](1, "green"); // replace
• [Link]("blue"); // remove by value (first
match)
• [Link](0); // remove by index
• boolean ok = [Link]("red");
• int i = [Link]("red"); // first index, -1 if not
found
• List<String> view = [Link](0, 1); // [0..1)
• [Link]([Link]()); // or
[Link](null) for natural
• [Link](String::toUpperCase);
• [Link](s -> [Link]() < 4);
• String[] arr = [Link](new String[0]); // or
[Link](String[]::new) (Java 11+)
- By polisetty Sai Teja 20
• var a = [Link]("x","y"); // •“[Link] is a
Immutabilit fixed-size, backed by array hotel room with nailed-
down furniture;
y & fixed- • // [Link]("z"); //
UnsupportedOperationException •[Link] is the museum
size traps: • [Link](0,"X"); // allowed (still fixed-
size)
—no touching.”

• var b = [Link]("x","y"); // truly


unmodifiable (Java 9+)
• // [Link](0,"X"); //
UnsupportedOperationException
• // [Link]("z"); //
UnsupportedOperationException

• var c =
[Link](new
ArrayList<>(a)); // read-only view of
a *copy*
- By polisetty Sai Teja 21
SubList is a view
• subList(from, to) returns a window into
the original list.
• Structural changes to parent or sublist
can cause
ConcurrentModificationException.
• If you need independence: new
ArrayList<>([Link](...))
var base = new ArrayList<>([Link](10,20,30,40,50));
var mid = [Link](1,4); // [20,30,40]
[Link](0, 200); // base now [10,200,30,40,50]
var copy = new ArrayList<>(mid);

- By polisetty Sai Teja 22


Iteration & fail-fast vs safe & sorting
• Fail fast iterator: • ListIterator for in-place edits +
for (String s : list) {
if ([Link]("X")) {
backwards
// [Link](s); // ❌ ListIterator<String> it2 = [Link]();
ConcurrentModificationException while ([Link]()) {
} String s = [Link]();
} if ([Link]("A")) [Link]("Alpha");
// Correct: if ([Link]("B")) [Link]("Beta"); // inserts before next()
Iterator<String> it = [Link](); }
while ([Link]()) { while ([Link]()) {
if ([Link]().startsWith("X")) [Link](); // ✅ [Link]([Link]());
} }
• Sorting & comparators:
• Safe iteration under [Link](null) → natural order (elements must be
Comparable).
concurrency Custom comparator:
CopyOnWriteArrayList: iteration sees a snapshot; [Link]([Link](User::score).reversed()
writes copy the array (costly for frequent writes).
.thenComparing(User::name));
[Link]: wrap + synchronized(list)
Why Comparator<? super T>? A comparator of a
{ for(...) } around iteration. supertype can compare subtypes—variance for
flexibility.

- By polisetty Sai Teja 23


Performance:

ArrayList appends are ensureCapacity(n) before trimToSize() can free LinkedList: each node Need a queue/stack?
amortized O(1); middle big appends avoids memory after big has pointers → higher Prefer ArrayDeque
inserts/removes O(n) repeated grows. removals. memory, slow random (faster, no capacity
(shift). access; shines only for boxing).
frequent head/tail ops
with iterator already
positioned.

- By polisetty Sai Teja 24


Spotify — Playlist editor (ordering, duplicates, sorting, safe removal)
record Track(String id, String title, boolean explicit, int
rating /*1..5*/) {} •Points to remember:
• Lists are ordered and allow
class Playlist { duplicates → perfect for playlists.
private final List<Track> tracks = new ArrayList<>(); • Use removeIf instead of removing
inside a for-each (avoids CME).
void add(Track t) { [Link](t); } // • subList is a view (changes reflect
duplicates allowed back).
void swap(int i, int j){ [Link](tracks, i, j); } //
reorder
void removeExplicit(){ [Link](Track::explicit); } //
safe bulk removal
void sortByRating()
{ [Link]([Link](Track::rating).reverse
d()); }

// "Up next" window (first N) -- returns a *view* of the list


List<Track> upNext(int n){
return [Link](0, [Link](n, [Link]())); //
view, not a copy - By polisetty Sai Teja 25
Example Use cases:

Tesla — Sensor sliding window Netflix — “Continue Watching” row


(last N / last via subList + binary (recency bump, pagination via
search) subList, iterator edits)
Charts of the last 60 seconds of telemetry. Recently watched titles show first; pagination shows
List idea: Keep readings time-sorted in a only first 10.
List<Reading>; cut a sliding window with subList. List idea: Keep a recency-ordered List<Title> and
bump to front on activity.

- By polisetty Sai Teja 26


Question Options
1 A List preserves _____. A) order B) hashing C) uniqueness D)
immutability
2 A List allows _____. A) duplicates B) nulls C) keys D)
sorting
3 Default go-to implementation? A) ArrayList B) LinkedList C) Vector D)
Stack
4 Random access time in ArrayList A) constant B) linear C) logarithmic D)
is _____. quadratic
5 Random access time in A) linear B) constant C) logarithmic D) Question Options
LinkedList is _____. quadratic
11 subList returns a _____. A) view B) copy C) clone D)
6 Preferred structure for A) ArrayDeque B) Vector C) ArrayList cache
queue/stack (not LinkedList) is D) Deque
_____. 12 [Link] is ____-size. A) fixed B) variable C)
dynamic D) infinite
7 Removing while for-each A) CME B) NPE C) OOM D) IAE
iterating causes _____. 13 [Link] is _____. A) unmodifiable B)
synchronized C) nullable D)
8 Safe bulk removal method is A) removeIf B) clear C) delete D) growable
_____. prune
14 Bulk iteration that won’t CME A) CopyOnWriteArrayList B)
9 remove(2) on List<Integer> A) index B) value C) key D) hash under reads-mostly workload: LinkedList C) Vector D) Stack
removes by _____.
15 Synchronized wrapper factory is A) synchronizedList B)
10 To remove the integer value 2, A) valueOf B) parseInt C) equals D) _____. syncList C) lockList D)
call _____. compare guardedList
16 To iterate a synchronized list A) synchronize B) finalize C)
safely, you must _____. serialize D) localize
17 Sorting natural order uses _____. A) sort B) order C) rank D)
align
18 Equality in indexOf relies on A) equals B) hashCode C)

Quiz - By polisetty Sai19


Teja
_____.
Marker interface for fast random
access is _____.
identity D) compareTo
A) RandomAccess27B)
FastAccess C) QuickIndex D)
Question Answers
1 A List preserves _____. A) order

2 A List allows _____. A) duplicates

3 Default go-to implementation? A) ArrayList

4 Random access time in ArrayList A) constant


is _____.
5 Random access time in A) linear
LinkedList is _____.
Question Options
6 Preferred structure for A) ArrayDeque
queue/stack (not LinkedList) is 11 subList returns a _____. A) view
_____.
12 [Link] is ____-size. A) fixed
7 Removing while for-each A) CME
iterating causes _____.
13 [Link] is _____. A) unmodifiable
8 Safe bulk removal method is A) removeIf
_____. 14 Bulk iteration that won’t CME A) CopyOnWriteArrayList
9 remove(2) on List<Integer> A) index under reads-mostly workload:
removes by _____. 15 Synchronized wrapper factory is A) synchronizedList
10 To remove the integer value 2, A) valueOf _____.
call _____. 16 To iterate a synchronized list A) synchronize
safely, you must _____.
17 Sorting natural order uses _____. A) sort

18 Equality in indexOf relies on A) equals


_____.
19 Marker interface for fast random A) RandomAccess

Answers
access is _____.
20 [Link]() (Java 16+) A) unmodifiable
- By polisetty Sai Teja returns a ____ list. 28
Map
• A Map<K,V> stores key → value pairs with
unique keys.
• Lookup by key (not by index).
• Typical ops: put, get, containsKey, remove,
size, isEmpty.
• Views: keySet(), values(), entrySet()
Map<String, String> phone = new HashMap<>();
[Link]("Alice", "999-111");
[Link]("Bob", "999-222");
[Link]([Link]("Alice")); // 999-
111
[Link]([Link]("Eve"));//
false

- By polisetty Sai Teja 29


record Driver(String id) {}​
Uber/Ola — live
record Cell(int x, int y) {}​
drivers by area
(computeIfAbse Map<Cell, List<Driver>> available
nt + removeIf) = ??? ;​
Match riders ​
fast by grid cell. void appear(Cell c, Driver d) {​
???​
}​

void acceptRide(Driver d) { ??? }​

- By polisetty Sai Teja 30


Implementation Use when Ordering Nulls Time (avg)
HashMap general purpose; fastest none allows 1 null key, get/put ~
lookups many null values O(1)
LinkedHashMap you need insertion order insertion or allows nulls O(1)
(or LRU) access
TreeMap you need sorted keys / sorted no null keys (NPE) O(log n)
range queries (Comparator)
ConcurrentHashMa multi-threaded none no nulls O(1)
p reads/writes without expected
external locks
EnumMap keys are a single enum enum order no null keys O(1)
type
WeakHashMap auto-remove entries none allows nulls O(1)
when keys GC’d (cache
keys)
IdentityHashMap key identity == (not none allows nulls O(1)
equals)
•Quick rules:
• Default: HashMap
Implementation • Need order or LRU cache: LinkedHashMap
• Need range queries (e.g., “next higher key”):
TreeMap Threads: ConcurrentHashMap (CHM)
- By polisetty Sai Teja 31
Core Api's:
Map<Integer,String> m = new HashMap<>();
[Link](101, "Alice");
[Link](101, "New"); // won't overwrite
[Link](102, "Bob");

String name = [Link](999, "Unknown");


Merge (word frequency):
[Link](102, "Bobby"); // replace if present Map<String,Integer> freq = new
[Link](103, k -> "Temp"); // lazy create HashMap<>();
for (String w : words) [Link](w, 1,
[Link](103, "X", (oldV, v) -> oldV + v); // combine Integer::sum);

// Iteration patterns
for ([Link]<Integer,String> e : [Link]()) {
[Link]([Link]() + " → " + [Link]());
}
[Link]((k,v) -> [Link](k + ":" + v));

- By polisetty Sai Teja 32


• LinkedHashMap (LRU cache in 6 lines):
class LruCache<K,V> extends LinkedHashMap<K,V> {
private final int cap;
LruCache(int cap) { super(16, 0.75f, true); [Link] =
cap; } // access-order
protected boolean removeEldestEntry([Link]<K,V>
e) { return size() > cap; }

Ordering }

tricks:
• TreeMap (sorted + range queries):
TreeMap<Integer,String> tm = new TreeMap<>();
[Link](10,"A"); [Link](20,"B"); [Link](30,"C");
[Link](21); // 20
[Link](19).getValue(); // "B"
[Link](10, true, 20, false); // [10..20)

- By polisetty Sai Teja 33


Equality, hashing & the #1 Map
bug:
HashMap uses hashCode() to choose a bucket, then equals() to
Maps rely on key equality: confirm.
Contract: if [Link](b) then [Link]()==[Link]().

Don’t mutate a key after put! If fields used in equals/hashCode change, the entry becomes “lost” in
the wrong bucket.

record UserId(String tenant, String id) { } // records give


correct equals+hashCode
Map<UserId, Profile> profiles = new HashMap<>();
UserId k = new UserId("t1", "42");
[Link](k, new Profile());
// [Link] = "t2"; // (if mutable) retrieval breaks!
- By polisetty Sai Teja 34
• Null rules (surprises):

Type Rule
HashMap/ allow one null key + many null values.
LinkedHashMap
TreeMap no null key with natural ordering (NPE).
ConcurrentHashMap no null keys or values (to avoid ambiguity
with “missing”).

Safe removal while iterating:


// ✅ safest: operate on view collections
[Link]().removeIf(e -> [Link]().isBlank());

// or explicit iterator
for (Iterator<[Link]<K,V>> it =
[Link]().iterator(); [Link]();) {
var e = [Link]();
if (shouldRemove(e)) [Link]();
}

- By polisetty Sai Teja 35


Concurrency quick guide:

To iterate safely: ConcurrentHash


HashMap + sync: Map<K,V> sm = Map:
No nulls; iterators don’t throw CME.
[Link](new Methods like
HashMap<>()); compute/merge/putIfAbsent are atomic
synchronized (sm) { for (var e : per key.
[Link]()) {/*...*/} }

- By polisetty Sai Teja 36


Immutability & factory
methods:

• ** [Link] rejects null keys/values and throws on modification.

Map<String,Integer> m1 = [Link]("a",1,"b",2); // unmodifiable


Map<String,Integer> m2 = [Link](m1); // defensive copy
(alsounmodifiable)
Map<String,Integer> ro = [Link](newHashMap<>(m1)); //
view of a copy

- By polisetty Sai Teja 37


record Driver(String id) {}
record Cell(int x, int y) {}
Map<Cell, List<Driver>> available = new
Uber/Ola — live HashMap<>();
drivers by area void appear(Cell c, Driver d) {
(computeIfAbse [Link](c, k -> new
nt + removeIf) ArrayList<>()).add(d);
}
Match riders void acceptRide(Driver d)
fast by grid cell. { [Link]().forEach(list ->
[Link](x -> [Link]().equals([Link]())));
}

**Why Map? Directly hits the right bucket (cell) for


O(1)-ish candidate retrieval.
**Slight improvement with concurrenthashmap.
- By polisetty Sai Teja 38
Example use cases:
Netflix — “continue watching”
Count minutes watched per title per profile.
progress (merge)

Spotify — user → playlists Each user has many playlists; each playlist
(computeIfAbsent) has tracks.

Tesla — time-series lookups Find the nearest reading at/after a


(TreeMap range/floor) timestamp.

Instagram/Twitter — trending
hashtags (ConcurrentHashMap + Many threads updating counts safely.
merge)
- By polisetty Sai Teja 39
Question Options
1 General-purpose Map with O(1) A) HashMap B) TreeMap C)
lookups? LinkedHashMap D) EnumMap
2 Map preserving insertion order? A) TreeMap B) LinkedHashMap C)
HashMap D) WeakHashMap
3 Map with keys kept sorted? A) TreeMap B) HashMap C)
LinkedHashMap D) IdentityHashMap
4 High-throughput thread-safe A) Hashtable B) ConcurrentHashMap
Map? C) WeakHashMap D) EnumMap
Question Options
5 Map specialized for enum keys? A) TreeMap B) EnumMap C) HashMap
D) IdentityHashMap 11 Return fallback when key A) getOrDefault B) orElse C)
missing: _____. optional D) defaultGet
6 Map comparing keys by A) IdentityHashMap B) HashMap C)
reference identity? TreeMap D) EnumMap 12 Remove only if key maps to A) remove B) delete C) clear
given value: _____. D) prune
7 Map that drops entries when A) WeakHashMap B)
keys are GC’d? ConcurrentHashMap C) LinkedHashMap 13 Unmodifiable factory with A) [Link] B) [Link] C)
D) TreeMap literals: _____. [Link] D)
[Link]
8 With new A) insertion B) access C) hash D)
LinkedHashMap(16,0.75f, true), random 14 Unmodifiable defensive copy of A) [Link] B) [Link] C)
ordering is _____. another Map: _____. unmodifiableMap D) clone
9 Create value container if A) merge B) computeIfAbsent C) 15 Nearest key ≤ k: _____. A) lowerKey B) ceilingKey C)
missing: _____. putIfAbsent D) getOrDefault floorKey D) higherKey
10 Combine counts (old + 1): _____. A) replace B) merge C) compute D) 16 Nearest entry ≥ k: _____. A) ceilingEntry B) floorEntry
put C) higherEntry D) lowerEntry
17 Range view between two keys: A) headMap B) tailMap C)
_____. subMap D) sliceMap
18 View for iterating key+value A) keySet B) values C)
pairs: _____. entrySet D) pairSet

Quiz 19

- By polisetty Sai Teja


20
Null keys in HashMap are
allowed: _____.
Null keys in ConcurrentHashMap
A) one B) many C) none D)
some
40
A) one B) many C) none D)
Question Answers
1 General-purpose Map with O(1) A) HashMap
lookups?
2 Map preserving insertion order? A) TreeMap

3 Map with keys kept sorted? A) TreeMap

4 High-throughput thread-safe A) Hashtable


Map?
5 Map specialized for enum keys? A) TreeMap
Question Answers
6 Map comparing keys by A) IdentityHashMap
reference identity? 11 Return fallback when key A) getOrDefault
missing: _____.
7 Map that drops entries when A) WeakHashMap
keys are GC’d? 12 Remove only if key maps to A) remove
given value: _____.
8 With new A) insertion
LinkedHashMap(16,0.75f, true), 13 Unmodifiable factory with A) [Link]
ordering is _____. literals: _____.
9 Create value container if A) merge 14 Unmodifiable defensive copy of A) [Link]
missing: _____. another Map: _____.
10 Combine counts (old + 1): _____. A) replace 15 Nearest key ≤ k: _____. A) lowerKey

16 Nearest entry ≥ k: _____. A) ceilingEntry

17 Range view between two keys: A) headMap


_____.
18 View for iterating key+value A) keySet
pairs: _____.
19 Null keys in HashMap are A) one

Answers - By polisetty Sai20


Teja
allowed: _____.
Null keys in ConcurrentHashMap A) one 41
are allowed: _____.

You might also like