BRAINBIT INFOTECH · RANCHI
COMPLETE CORE JAVA COURSE · PART 4 OF 5

Collections, Generics & Streams

Use enums, records and generics, store data in Lists, Sets and Maps, and process it with lambdas and streams.

4 modules~19.5 hours40 practice examplesNeeds Parts 1-3

By the end of this part you can build

  • A shopping cart with ArrayList
  • A phone book and word counter with HashMap
  • A leaderboard with Comparator
  • Sales reports with streams

Every code example has a ▶ Run button. Click ✎ Edit, or press L, to open the Code Lab.

ROADMAP FOR THIS PART

Module 14Wrappers, Enums, Records and Generics4.5 h
Module 15Collections I: List, Set, Queue5 h
Module 16Collections II: Maps and Sorting5 h
Module 17Lambdas and the Stream API5 h
{ } Java java Main.java main()
JavaBefore we begin

How to Use This Part

Suggested teaching hours per module (Part 4)0244.5 hM145 hM155 hM165 hM17

Every module has

  1. 1
    A "Where is it used?" diagram of real projects
  2. 2
    Concept in short + code + terminal: press ▶ Run to watch the output appear
  3. 3
    Step-through animations recorded from the real JVM: variables, method calls, objects
  4. 4
    A Code Lab: edit, copy or download the code and run it with java Main.java
  5. 5
    10 practice examples: 5 Easy, 3 Medium, 2 Hard, with solutions
  6. 6
    An animated recap + quiz
Controls→ next, ← back, M menu, L Code Lab, F fullscreen.
Running JavaEvery output on the slides was produced by compiling and running the code with a real JDK 21, so the slides work offline. On your computer (JDK 11+), run a single file with java Main.java in the folder D:\java-practice.
MODULE 14

Wrappers, Enums, Records and Generics

⏱ 4.5 hours10 practice examplesStep-through animationsCode Lab

You will learn

  • Wrapper classes, autoboxing and parsing
  • enum: a fixed set of named constants
  • enums with fields, methods and switch
  • record: one-line data classes
  • Generics: type-safe classes and methods

You will build

  • Order status tracking with enum
  • Data transfer records
  • A generic Pair and Box
<T>enum Status { PAID }record Point(int x, int y)
Module 14Real-world use

Where Is This Used in Real Projects?

these toolssafer, cleaner types📦Order statusPLACED, SHIPPED🚦Traffic signalsRED, GREEN🌐API responsesrecords (DTOs)📋CollectionsList<String>🔢FormsInteger.parseInt📅Days, monthsDayOfWeek enum

Real projects that use this

  • Zomato-like apps track OrderStatus.OUT_FOR_DELIVERY with an enum, not a string
  • Spring Boot APIs send and receive records as JSON
  • Every collection is generic: List<Student>, Map<String, Integer>
  • Wrappers convert text from forms and files into numbers
Module 14Wrappers

Wrapper Classes: Primitives as Objects

int 42primitiveInteger object42autoboxingunboxingcollections (ArrayList, HashMap) can store only objects, so Java boxes for you
PrimitiveWrapper
intInteger
doubleDouble
charCharacter
booleanBoolean
longLong
💡 Concept in shortEach primitive has a wrapper class that holds it as an object. Java converts automatically: autoboxing (int to Integer) and unboxing (Integer to int). Wrappers also give useful static methods.
jshell (Java interactive shell)
// jshell: type Java and see the answer at once. Press Next line.
0 / 8
Module 14enum

enum: A Fixed Set of Named Values

Main.java  JAVA
1enum Signal { RED, YELLOW, GREEN }
2
3public class Main {
4 static String action(Signal s) {
5 return switch (s) {
6 case RED -> "Stop";
7 case YELLOW -> "Get ready";
8 case GREEN -> "Go";
9 };
10 }
11
12 public static void main(String[] args) {
13 Signal now = Signal.RED;
14 System.out.println(now + ": " + action(now));
15 for (Signal s : Signal.values()) {
16 System.out.println(s.ordinal() + " " + s + " -> " + action(s));
17 }
18 Signal fromText = Signal.valueOf("GREEN");
19 System.out.println("Parsed: " + fromText);
20 }
21}
Terminal
D:\java-practice> java Main.java
RED: Stop
0 RED -> Stop
1 YELLOW -> Get ready
2 GREEN -> Go
Parsed: GREEN
💡 Concept in shortAn enum defines a type whose only values are the listed constants. The compiler stops typos like "Gren" that a String would allow. values() lists them; valueOf() converts text.
Rememberswitch over an enum must cover every value (or have default), so you never forget a case.
Module 14Rich enum

Enums with Fields and Methods: Order Status

Main.java  JAVA
1enum OrderStatus {
2 PLACED("Order placed", 10),
3 PACKED("Packed at store", 30),
4 SHIPPED("On the way", 70),
5 DELIVERED("Delivered", 100);
6
7 private final String label;
8 private final int progress;
9
10 OrderStatus(String label, int progress) { // enum constructor
11 this.label = label;
12 this.progress = progress;
13 }
14 String bar() { return "#".repeat(progress / 10) + ".".repeat(10 - progress / 10); }
15 OrderStatus next() {
16 return this == DELIVERED ? DELIVERED : values()[ordinal() + 1];
17 }
18 String getLabel() { return label; }
19}
20
21public class Main {
22 public static void main(String[] args) {
23 OrderStatus s = OrderStatus.PLACED;
24 for (int i = 0; i < 4; i++) {
25 System.out.printf("%-9s [%s] %s%n", s, s.bar(), s.getLabel());
26 s = s.next();
27 }
28 }
29}
Terminal
D:\java-practice> java Main.java
PLACED [#.........] Order placed
PACKED [###.......] Packed at store
SHIPPED [#######...] On the way
DELIVERED [##########] Delivered
💡 Concept in shortEnum constants are real objects: an enum can have fields, a constructor and methods. Each constant passes its own data, like a label and a progress percentage.
Module 14record

record: A Data Class in One Line

Main.java  JAVA
1record Student(String name, int roll, double marks) {
2 Student { // validation
3 if (marks < 0 || marks > 100) throw new IllegalArgumentException("bad marks");
4 }
5 String grade() { return marks >= 90 ? "A+" : marks >= 75 ? "A" : "B"; }
6}
7
8public class Main {
9 public static void main(String[] args) {
10 Student s = new Student("Priya", 14, 91.5);
11 System.out.println(s); // toString for free
12 System.out.println(s.name() + " got " + s.grade()); // accessor: name()
13 Student t = new Student("Priya", 14, 91.5);
14 System.out.println("equal? " + s.equals(t)); // equals for free
15 }
16}
Terminal
D:\java-practice> java Main.java
Student[name=Priya, roll=14, marks=91.5]
Priya got A+
equal? true
💡 Concept in shortA record (Java 16+) creates an immutable data class with a constructor, getters (name()), equals, hashCode and toString automatically. Perfect for data carried between parts of an app.
Class with 3 fieldsrecord
~40 lines1 line
setters possibleimmutable
getName()name()
Module 14Generics

Generics: One Class for Any Type, Still Type-Safe

Main.java  JAVA
1class Box<T> { // T = a type chosen later
2 private T item;
3 void put(T item) { this.item = item; }
4 T get() { return item; }
5}
6
7public class Main {
8 public static void main(String[] args) {
9 Box<String> gift = new Box<>();
10 gift.put("Smart watch");
11 String g = gift.get(); // no cast needed
12
13 Box<Integer> marks = new Box<>();
14 marks.put(95);
15 int m = marks.get() + 5; // unboxing
16
17 System.out.println(g + ", " + m);
18 // gift.put(42); // compile ERROR: not a String
19 }
20}
Terminal
D:\java-practice> java Main.java
Smart watch, 100
💡 Concept in shortGenerics let a class or method work with any type while the compiler still checks types. Box<String> accepts only Strings. <> (diamond) lets Java infer the type.
RememberThis is how ArrayList<String> and HashMap<String, Integer> work (Modules 15-16).
Module 14Generic methods

Generic Methods and Bounded Types

Main.java  JAVA
1import java.util.Arrays;
2
3record Pair<A, B>(A first, B second) { }
4
5public class Main {
6 static <T> void printAll(T[] items) { // any type
7 for (T x : items) System.out.print(x + " | ");
8 System.out.println();
9 }
10 static <T extends Comparable<T>> T max(T[] items) { // only comparable types
11 T best = items[0];
12 for (T x : items) if (x.compareTo(best) > 0) best = x;
13 return best;
14 }
15
16 public static void main(String[] args) {
17 Integer[] runs = {45, 102, 67};
18 String[] cities = {"Ranchi", "Bokaro", "Deoghar"};
19 printAll(runs);
20 printAll(cities);
21 System.out.println("max run: " + max(runs) + ", last city: " + max(cities));
22 Pair<String, Integer> p = new Pair<>("Hundru Falls", 98);
23 System.out.println(p.first() + " is " + p.second() + " m high");
24 }
25}
Terminal
D:\java-practice> java Main.java
45 | 102 | 67 |
Ranchi | Bokaro | Deoghar |
max run: 102, last city: Ranchi
Hundru Falls is 98 m high
💡 Concept in short<T> before the return type makes a generic method. <T extends Comparable<T>> is a bound: only types that can be compared are allowed. Records can be generic too.
Module 14Hands-on

Code Lab: Try It Yourself

Main.java
Output of the starter code
D:\java-practice> java Main.java
PizzaOrder[flavour=Paneer Tikka, size=MEDIUM, qty=2] = Rs 698
PizzaOrder[flavour=Margherita, size=LARGE, qty=1] = Rs 499
Bill: Rs 1197
[SMALL, MEDIUM, LARGE]
Change the code, then run it on your computer: ⬇ Download → open a terminal in that folder → java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).
Your tasks
  1. Add an EXTRA_LARGE size
  2. Add a Crust enum (THIN, CHEESE_BURST +Rs 99)
  3. Make the record validate qty > 0
  4. Write a generic method <T> T last(T[] a)
PracticePractice 1 of 10 · Easy

Wrapper Conversions

EasyScenario. A data entry screen converts text to numbers and back.
💡 Concept used: parseXxx, valueOf and toString of wrapper classes.

Your tasks

  1. Parse int, double, boolean from text
  2. Convert numbers back to text
  3. Show MAX and MIN values
🏢 Used in real projects: Every form and file reader converts text to numbers with wrapper methods.
Wrappers.java  JAVA
1public class Wrappers {
2 public static void main(String[] args) {
3 int qty = Integer.parseInt("12");
4 double price = Double.parseDouble("45.50");
5 boolean paid = Boolean.parseBoolean("true");
6 System.out.println("Total: " + qty * price + ", paid " + paid);
7 String s = String.valueOf(qty * price);
8 System.out.println("As text: \"" + s + "\" length " + s.length());
9 System.out.println("int range: " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
10 System.out.println("Binary of 12: " + Integer.toBinaryString(12));
11 }
12}
PracticePractice 2 of 10 · Easy

Days of the Week Enum

EasyScenario. A school timetable app knows which days are holidays.
💡 Concept used: An enum with a method; values() for looping.

Your tasks

  1. enum Day MON..SUN
  2. isWeekend() method
  3. Print each day with "school" or "holiday"
🏢 Used in real projects: java.time.DayOfWeek is exactly such an enum.
Timetable.java  JAVA
1enum Day {
2 MON, TUE, WED, THU, FRI, SAT, SUN;
3 boolean isHoliday() { return this == SUN; }
4}
5
6public class Timetable {
7 public static void main(String[] args) {
8 for (Day d : Day.values()) {
9 System.out.println(d + (d.isHoliday() ? " - holiday" : " - school"));
10 }
11 }
12}
PracticePractice 3 of 10 · Easy

Student Record

EasyScenario. A results API sends student data as records.
💡 Concept used: record gives constructor, accessors, toString and equals automatically.

Your tasks

  1. record Result(name, roll, percent)
  2. Create 3 records
  3. Print and compare two
🏢 Used in real projects: DTOs (data transfer objects) in REST APIs are written as records.
Results.java  JAVA
1record Result(String name, int roll, double percent) { }
2
3public class Results {
4 public static void main(String[] args) {
5 Result a = new Result("Ankita", 3, 88.4);
6 Result b = new Result("Bhola", 7, 72.0);
7 Result c = new Result("Ankita", 3, 88.4);
8 System.out.println(a);
9 System.out.println(b.name() + " scored " + b.percent());
10 System.out.println("a equals c? " + a.equals(c));
11 }
12}
PracticePractice 4 of 10 · Easy

Electricity Slab Enum

EasyScenario. JBVNL-style slabs: rate depends on units used.
💡 Concept used: Enum constants carrying data (range and rate) and a static finder method.

Your tasks

  1. enum Slab with min, max, rate
  2. static Slab of(units)
  3. Print slab and bill for 4 consumers
🏢 Used in real projects: Tariff tables, tax slabs and membership tiers are modelled as enums.
SlabBill.java  JAVA
1enum Slab {
2 LOW(0, 100, 4.0), MID(101, 200, 5.5), HIGH(201, 400, 6.8), PEAK(401, Integer.MAX_VALUE, 8.0);
3 final int min, max; final double rate;
4 Slab(int min, int max, double rate) { this.min = min; this.max = max; this.rate = rate; }
5 static Slab of(int units) {
6 for (Slab s : values()) if (units >= s.min && units <= s.max) return s;
7 throw new IllegalArgumentException("bad units");
8 }
9}
10
11public class SlabBill {
12 public static void main(String[] args) {
13 int[] usage = {85, 160, 340, 520};
14 for (int u : usage) {
15 Slab s = Slab.of(u);
16 System.out.printf("%3d units -> %-4s @ Rs %.1f = Rs %.2f%n", u, s, s.rate, u * s.rate);
17 }
18 }
19}
PracticePractice 5 of 10 · Easy

Generic Pair Utility

EasyScenario. Return two values from a method (min and max marks) using a generic pair.
💡 Concept used: A generic record Pair<A, B> lets one method return two values of any type.

Your tasks

  1. record Pair<A, B>
  2. method minMax(int[]) returns Pair<Integer, Integer>
  3. method topper returns Pair<String, Integer>
🏢 Used in real projects: Map.Entry<K, V> in Java is a generic pair used everywhere.
PairDemo.java  JAVA
1record Pair<A, B>(A first, B second) { }
2
3public class PairDemo {
4 static Pair<Integer, Integer> minMax(int[] a) {
5 int lo = a[0], hi = a[0];
6 for (int x : a) { lo = Math.min(lo, x); hi = Math.max(hi, x); }
7 return new Pair<>(lo, hi);
8 }
9 static Pair<String, Integer> topper(String[] names, int[] marks) {
10 int best = 0;
11 for (int i = 1; i < marks.length; i++) if (marks[i] > marks[best]) best = i;
12 return new Pair<>(names[best], marks[best]);
13 }
14 public static void main(String[] args) {
15 int[] m = {67, 92, 45, 88};
16 String[] n = {"Aman", "Bina", "Chirag", "Diya"};
17 Pair<Integer, Integer> mm = minMax(m);
18 System.out.println("Lowest " + mm.first() + ", highest " + mm.second());
19 Pair<String, Integer> t = topper(n, m);
20 System.out.println("Topper: " + t.first() + " (" + t.second() + ")");
21 }
22}
PracticePractice 6 of 10 · Medium

Order Tracking State Machine

MediumScenario. A food delivery order moves PLACED -> ACCEPTED -> COOKING -> OUT_FOR_DELIVERY -> DELIVERED, or CANCELLED only before cooking.
💡 Concept used: An enum that decides allowed transitions (a state machine).

Your tasks

  1. enum Status with canMoveTo(Status next)
  2. Order record/class holding the status
  3. Try valid and invalid moves
  4. Print the timeline
🏢 Used in real projects: Swiggy/Zomato-style tracking and every workflow system use status enums with rules.
Tracking.java  JAVA
1enum Status {
2 PLACED, ACCEPTED, COOKING, OUT_FOR_DELIVERY, DELIVERED, CANCELLED;
3 boolean canMoveTo(Status n) {
4 if (n == CANCELLED) return this == PLACED || this == ACCEPTED;
5 return this != CANCELLED && this != DELIVERED && n.ordinal() == ordinal() + 1;
6 }
7}
8
9public class Tracking {
10 public static void main(String[] args) {
11 Status s = Status.PLACED;
12 Status[] events = {Status.ACCEPTED, Status.DELIVERED, Status.COOKING, Status.CANCELLED, Status.OUT_FOR_DELIVERY, Status.DELIVERED};
13 System.out.println("Order #A77: " + s);
14 for (Status e : events) {
15 if (s.canMoveTo(e)) {
16 s = e;
17 System.out.println(" -> " + s);
18 } else {
19 System.out.println(" x cannot go from " + s + " to " + e);
20 }
21 }
22 }
23}
PracticePractice 7 of 10 · Medium

Generic Stack for Undo

MediumScenario. A text editor keeps an undo history; the same stack class should work for Strings and Integers.
💡 Concept used: A generic class backed by an array; type parameter T in fields and methods.

Your tasks

  1. class Stack<T> with push, pop, peek, isEmpty
  2. Use Stack<String> for edits
  3. Use Stack<Integer> for cursor positions
  4. Undo twice
🏢 Used in real projects: Editors, browsers (back button) and calculators use stacks; Java provides ArrayDeque.
Undo.java  JAVA
1class Stack<T> {
2 private Object[] data = new Object[10];
3 private int size;
4 void push(T x) { data[size++] = x; }
5 @SuppressWarnings("unchecked")
6 T pop() { return (T) data[--size]; }
7 @SuppressWarnings("unchecked")
8 T peek() { return (T) data[size - 1]; }
9 boolean isEmpty() { return size == 0; }
10}
11
12public class Undo {
13 public static void main(String[] args) {
14 Stack<String> history = new Stack<>();
15 Stack<Integer> cursor = new Stack<>();
16 String[] edits = {"Hello", "Hello Ranchi", "Hello Ranchi!!"};
17 for (String e : edits) { history.push(e); cursor.push(e.length()); }
18 System.out.println("Now: " + history.peek() + " (cursor " + cursor.peek() + ")");
19 history.pop(); cursor.pop();
20 System.out.println("Undo: " + history.peek() + " (cursor " + cursor.peek() + ")");
21 history.pop(); cursor.pop();
22 System.out.println("Undo: " + history.peek() + " (cursor " + cursor.peek() + ")");
23 }
24}
PracticePractice 8 of 10 · Medium

Bounded Generic Statistics

MediumScenario. One statistics method should work for Integer marks and Double prices but not for Strings.
💡 Concept used: Bounded type <T extends Number> lets you call doubleValue() on any numeric wrapper.

Your tasks

  1. static <T extends Number> double average(T[] a)
  2. max using doubleValue()
  3. Use with Integer[] and Double[]
  4. Show that String[] would not compile (comment)
🏢 Used in real projects: Library code (charts, reports) is generic so it works for any numeric data.
Stats.java  JAVA
1public class Stats {
2 static <T extends Number> double average(T[] a) {
3 double s = 0;
4 for (T x : a) s += x.doubleValue();
5 return s / a.length;
6 }
7 static <T extends Number> T max(T[] a) {
8 T best = a[0];
9 for (T x : a) if (x.doubleValue() > best.doubleValue()) best = x;
10 return best;
11 }
12 public static void main(String[] args) {
13 Integer[] marks = {78, 91, 66, 85};
14 Double[] prices = {45.5, 120.0, 99.99};
15 System.out.printf("Marks avg %.2f, max %d%n", average(marks), max(marks));
16 System.out.printf("Prices avg %.2f, max %.2f%n", average(prices), max(prices));
17 // average(new String[]{"a"}); // ERROR: String is not a Number
18 }
19}
PracticePractice 9 of 10 · Hard

Inventory with Enums, Records and Generics

HardScenario. A medical store tracks medicines by category; a generic Result type returns success or an error message.
💡 Concept used: Combining all four tools: enum categories with GST, records for items, a generic Result<T>, wrapper parsing of input lines.

Your tasks

  1. enum Category with gst rate
  2. record Medicine(name, Category, price, stock)
  3. record Result<T>(T value, String error) with static ok/fail
  4. parse(String line) returns Result<Medicine>; print valid items and errors
🏢 Used in real projects: Modern Java services combine enums, records and generic result types exactly like this.
Pharmacy.java  JAVA
1enum Category {
2 TABLET(12), SYRUP(12), DEVICE(18), AYURVEDIC(5);
3 final int gst;
4 Category(int g) { gst = g; }
5}
6record Medicine(String name, Category cat, double price, int stock) {
7 double priceWithGst() { return price * (100 + cat.gst) / 100; }
8}
9record Result<T>(T value, String error) {
10 static <T> Result<T> ok(T v) { return new Result<>(v, null); }
11 static <T> Result<T> fail(String e) { return new Result<>(null, e); }
12 boolean isOk() { return error == null; }
13}
14
15public class Pharmacy {
16 static Result<Medicine> parse(String line) {
17 String[] f = line.split(";");
18 if (f.length != 4) return Result.fail("expected 4 fields: " + line);
19 try {
20 return Result.ok(new Medicine(f[0], Category.valueOf(f[1]), Double.parseDouble(f[2]), Integer.parseInt(f[3])));
21 } catch (IllegalArgumentException e) { // also catches NumberFormatException
22 return Result.fail("bad value in: " + line);
23 }
24 }
25 public static void main(String[] args) {
26 String[] lines = {"Paracetamol 500;TABLET;30;200", "Cough syrup;SYRUP;95.5;40", "BP monitor;DEVICE;1499;x", "Chyawanprash;AYURVEDIC;320;25", "Thermometer;GADGET;250;10"};
27 for (String l : lines) {
28 Result<Medicine> r = parse(l);
29 if (r.isOk()) {
30 Medicine m = r.value();
31 System.out.printf("%-16s %-9s Rs %8.2f (incl %d%% GST) stock %d%n", m.name(), m.cat(), m.priceWithGst(), m.cat().gst, m.stock());
32 } else {
33 System.out.println("ERROR " + r.error());
34 }
35 }
36 }
37}
PracticePractice 10 of 10 · Hard

Generic Leaderboard

HardScenario. A quiz app ranks players; the same leaderboard class should rank any record that can be compared.
💡 Concept used: A generic class with a bound T extends Comparable<T>, records implementing Comparable, and insertion into a sorted array.

Your tasks

  1. class Leaderboard<T extends Comparable<T>> keeping top N sorted
  2. record Player(name, score) implements Comparable
  3. add() keeps only top 3
  4. Reuse it for record Team(name, points)
🏢 Used in real projects: Generic, bounded components are how libraries like Collections.sort work for any type.
Board.java  JAVA
1import java.util.Arrays;
2
3class Leaderboard<T extends Comparable<T>> {
4 private final Object[] top;
5 private int size;
6 Leaderboard(int n) { top = new Object[n]; }
7 @SuppressWarnings("unchecked")
8 void add(T x) {
9 if (size < top.length) top[size++] = x;
10 else if (x.compareTo((T) top[size - 1]) > 0) top[size - 1] = x;
11 else return;
12 int i = size - 1;
13 while (i > 0 && ((T) top[i]).compareTo((T) top[i - 1]) > 0) {
14 Object t = top[i]; top[i] = top[i - 1]; top[i - 1] = t; i--;
15 }
16 }
17 String show() { return Arrays.toString(Arrays.copyOf(top, size)); }
18}
19record Player(String name, int score) implements Comparable<Player> {
20 public int compareTo(Player o) { return Integer.compare(score, o.score); }
21}
22record Team(String name, double points) implements Comparable<Team> {
23 public int compareTo(Team o) { return Double.compare(points, o.points); }
24}
25
26public class Board {
27 public static void main(String[] args) {
28 Leaderboard<Player> lb = new Leaderboard<>(3);
29 int[] sc = {40, 75, 62, 90, 55};
30 String[] nm = {"Asha", "Bunty", "Chinu", "Dev", "Ekta"};
31 for (int i = 0; i < sc.length; i++) { lb.add(new Player(nm[i], sc[i])); System.out.println(lb.show()); }
32 Leaderboard<Team> tb = new Leaderboard<>(2);
33 tb.add(new Team("Ranchi Rhinos", 12.5)); tb.add(new Team("Dhanbad Dynamos", 15)); tb.add(new Team("Bokaro Bulls", 9));
34 System.out.println(tb.show());
35 }
36}
Module 14Recap

Module 14 Recap & Quiz

What you learned

  • 1Wrappers: Integer, Double...; autoboxing/unboxing; parseInt; compare with equals
  • 2enum: fixed named constants; values(), valueOf(), switch
  • 3Enums can have fields, constructors and methods
  • 4record: immutable data class with free accessors, equals, toString
  • 5Generics Box<T>: one class, any type, compile-time safety
  • 6Generic methods <T>, bounds <T extends Number>

Quick quiz

Integer.parseInt("42") returns...

It returns a primitive int.

Accessor for field name in a record is...

Records use the field name as method name.

Box<String> b; b.put(5);

Generics catch the wrong type at compile time.
MODULE 15

Collections I: List, Set, Queue

⏱ 5 hours10 practice examplesStep-through animationsCode Lab

You will learn

  • The Collections Framework: why and what
  • ArrayList: a growable list
  • Iterating: for-each, index, Iterator, removeIf
  • HashSet, LinkedHashSet, TreeSet: unique values
  • Queue and Deque: ArrayDeque, PriorityQueue

You will build

  • A shopping cart and wishlist
  • Unique visitor and tag tracking
  • A hospital token queue
List<>new ArrayList&lt;&gt;()set.add(x)
Module 15Real-world use

Where Is This Used in Real Projects?

collectionsdata that grows🛒CartsList<Item>🏷TagsSet<String>🏥TokensQueue<Patient>🔍Search historyDeque⏳Task schedulersPriorityQueue👥FollowersSet<User>

Real projects that use this

  • Arrays have a fixed size; real data grows and shrinks, so apps use collections
  • Almost every Java method in a real project returns or takes a List
  • Sets remove duplicate emails, tags and roll numbers automatically
  • Queues serve customers, print jobs and messages in order
Module 15Big picture

The Collections Framework Family

CollectioninterfaceListordered, duplicatesSetno duplicatesQueuefirst in, first outArrayListLinkedListHashSetTreeSetArrayDequePriorityQueueMap (key -> value) is separate: Module 16
💡 Concept in shortThe Collections Framework (java.util) gives ready-made data structures. Interfaces (List, Set, Queue) say what you can do; classes (ArrayList, HashSet...) are the implementations.
NeedUse
ordered list, index accessArrayList
no duplicates, fast checkHashSet
sorted unique valuesTreeSet
first come first servedArrayDeque
most urgent firstPriorityQueue
RememberDeclare with the interface: List<String> names = new ArrayList<>();
Module 15ArrayList

ArrayList: A List That Grows

Main.java  JAVA
1import java.util.ArrayList;
2import java.util.List;
3
4public class Main {
5 public static void main(String[] args) {
6 List<String> cart = new ArrayList<>();
7 cart.add("Rice 5kg");
8 cart.add("Dal 1kg");
9 cart.add("Oil 1L");
10 cart.add(1, "Sugar 1kg"); // insert at index 1
11 System.out.println(cart + " size " + cart.size());
12
13 System.out.println("First: " + cart.get(0));
14 cart.set(2, "Moong dal 1kg"); // replace
15 cart.remove("Oil 1L"); // by value
16 System.out.println("Has sugar? " + cart.contains("Sugar 1kg"));
17 System.out.println("Index of sugar: " + cart.indexOf("Sugar 1kg"));
18 System.out.println(cart);
19 cart.clear();
20 System.out.println("Empty? " + cart.isEmpty());
21 }
22}
Terminal
D:\java-practice> java Main.java
[Rice 5kg, Sugar 1kg, Dal 1kg, Oil 1L] size 4
First: Rice 5kg
Has sugar? true
Index of sugar: 1
[Rice 5kg, Sugar 1kg, Moong dal 1kg]
Empty? true
💡 Concept in shortArrayList is like an array that resizes itself. It keeps insertion order, allows duplicates and gives index access. Store objects only: List<Integer>, not List<int>.
MethodDoes
add(x) / add(i, x)append / insert
get(i), set(i, x)read / replace
remove(i or x)delete
size(), contains(x)count / search
Module 15Animation

Watch an ArrayList Change

List<String> cart

0
"Rice"
1
"Dal"
List<String> cart = new ArrayList<>(List.of("Rice", "Dal"));
Starting value.
💡 Concept in shortUnlike an array, the size changes on every add or remove. Inserting or removing in the middle shifts later elements, so indexes change.
Common mistakeremove(1) on a List<Integer> removes index 1; use remove(Integer.valueOf(1)) to remove the value 1.
Module 15Iterate

Looping Through a List Safely

Main.java  JAVA
1import java.util.*;
2
3public class Main {
4 public static void main(String[] args) {
5 List<Integer> marks = new ArrayList<>(List.of(78, 28, 91, 30, 66, 12));
6
7 for (int m : marks) System.out.print(m + " "); // for-each
8 System.out.println();
9 for (int i = 0; i < marks.size(); i++) { // index
10 if (i % 2 == 0) System.out.print("[" + i + "]=" + marks.get(i) + " ");
11 }
12 System.out.println();
13
14 Iterator<Integer> it = marks.iterator(); // remove while looping
15 while (it.hasNext()) {
16 if (it.next() < 33) it.remove();
17 }
18 System.out.println("Passed: " + marks);
19
20 List<Integer> extra = new ArrayList<>(List.of(5, 40, 8));
21 extra.removeIf(x -> x < 10); // modern way
22 System.out.println("removeIf: " + extra);
23 }
24}
Terminal
D:\java-practice> java Main.java
78 28 91 30 66 12
[0]=78 [2]=91 [4]=66
Passed: [78, 91, 66]
removeIf: [40]
💡 Concept in shortUse for-each to read. To remove while looping, use an Iterator or removeIf; removing inside a for-each throws ConcurrentModificationException.
RememberList.of(...) makes an unmodifiable list; wrap it in new ArrayList<>(...) to change it.
Module 15Objects in lists

A List of Objects + Collections Utilities

Main.java  JAVA
1import java.util.*;
2
3record Item(String name, double price, int qty) {
4 double total() { return price * qty; }
5}
6
7public class Main {
8 public static void main(String[] args) {
9 List<Item> cart = new ArrayList<>();
10 cart.add(new Item("Earphones", 799, 1));
11 cart.add(new Item("Notebook", 45, 6));
12 cart.add(new Item("Pen pack", 120, 2));
13
14 double sum = 0;
15 for (Item i : cart) sum += i.total();
16 System.out.println(cart.size() + " items, bill Rs " + sum);
17
18 List<String> names = new ArrayList<>();
19 for (Item i : cart) names.add(i.name());
20 Collections.sort(names);
21 System.out.println("Sorted: " + names);
22 Collections.reverse(names);
23 System.out.println("Reversed: " + names + ", max: " + Collections.max(names));
24 }
25}
Terminal
D:\java-practice> java Main.java
3 items, bill Rs 1309.0
Sorted: [Earphones, Notebook, Pen pack]
Reversed: [Pen pack, Notebook, Earphones], max: Pen pack
💡 Concept in shortA List<Item> holds objects; loop to compute totals. The Collections class (with an s) has static helpers: sort, reverse, shuffle, max, min, frequency.
Module 15Set

Sets: No Duplicates Allowed

Main.java  JAVA
1import java.util.*;
2
3public class Main {
4 public static void main(String[] args) {
5 String[] visits = {"aman", "riya", "aman", "zoya", "riya", "kunal", "aman"};
6
7 Set<String> hash = new HashSet<>();
8 Set<String> linked = new LinkedHashSet<>();
9 Set<String> tree = new TreeSet<>();
10 for (String v : visits) {
11 hash.add(v);
12 linked.add(v);
13 tree.add(v);
14 }
15 System.out.println("Visits: " + visits.length + ", unique: " + hash.size());
16 System.out.println("LinkedHashSet (first-seen order): " + linked);
17 System.out.println("TreeSet (sorted): " + tree);
18 System.out.println("add aman again? " + hash.add("aman"));
19 System.out.println("contains zoya? " + hash.contains("zoya"));
20 }
21}
Terminal
D:\java-practice> java Main.java
Visits: 7, unique: 4
LinkedHashSet (first-seen order): [aman, riya, zoya, kunal]
TreeSet (sorted): [aman, kunal, riya, zoya]
add aman again? false
contains zoya? true
💡 Concept in shortA Set keeps each value only once. add returns false for a duplicate. HashSet is fastest (no order), LinkedHashSet keeps insertion order, TreeSet keeps values sorted.
RememberSets use equals and hashCode to spot duplicates: override them in your own classes (Module 11).
Module 15Set maths

Set Operations: Union, Intersection, Difference

cricketfootballAmanDevRiyaZoyaKunal
jshell (Java interactive shell)
// jshell: type Java and see the answer at once. Press Next line.
0 / 8
💡 Concept in shortaddAll = union, retainAll = intersection, removeAll = difference. Copy first, because these methods change the set.
🤝

Real use

Students in both clubs; customers who bought A but not B; common friends.
Module 15Queue

Queue and Deque: First In, First Out (and Stacks)

Main.java  JAVA
1import java.util.*;
2
3public class Main {
4 public static void main(String[] args) {
5 Queue<String> counter = new ArrayDeque<>(); // token queue
6 counter.offer("T101 Ramesh");
7 counter.offer("T102 Sunita");
8 counter.offer("T103 Arif");
9 System.out.println("Next: " + counter.peek());
10 while (!counter.isEmpty()) {
11 System.out.println("Serving " + counter.poll());
12 }
13
14 Deque<String> back = new ArrayDeque<>(); // stack: last in, first out
15 back.push("home");
16 back.push("products");
17 back.push("cart");
18 System.out.println("Back -> " + back.pop() + ", then " + back.peek());
19 }
20}
Terminal
D:\java-practice> java Main.java
Next: T101 Ramesh
Serving T101 Ramesh
Serving T102 Sunita
Serving T103 Arif
Back -> cart, then products
💡 Concept in shortA Queue serves in arrival order: offer adds at the back, poll removes from the front, peek looks. ArrayDeque also works as a stack with push/pop (last in, first out).
QueueStack
offer / poll / peekpush / pop / peek
ticket counterbrowser back button
FIFOLIFO
Module 15Animation

Watch a Queue at the Hospital Counter

Queue<String> q

0
"T101"
1
"T102"
Queue<String> q = new ArrayDeque<>(List.of("T101", "T102"));
Starting value.
💡 Concept in shortQueues are fair: whoever came first is served first. Index 0 is the front. poll() returns null on an empty queue, while remove() throws an exception.
🚨

PriorityQueue

Serves the smallest (or most urgent) item first, not the oldest: emergency patients, cheapest delivery, next timer.
Module 15PriorityQueue

PriorityQueue: Most Urgent First

Main.java  JAVA
1import java.util.*;
2
3record Patient(String name, int severity) { } // 1 = most urgent
4
5public class Main {
6 public static void main(String[] args) {
7 PriorityQueue<Patient> er = new PriorityQueue<>(Comparator.comparingInt(Patient::severity));
8 er.add(new Patient("Mohan (fever)", 4));
9 er.add(new Patient("Seema (accident)", 1));
10 er.add(new Patient("Rafiq (fracture)", 2));
11 er.add(new Patient("Lata (cough)", 5));
12 while (!er.isEmpty()) {
13 Patient p = er.poll();
14 System.out.println("Treating " + p.name() + " [level " + p.severity() + "]");
15 }
16 PriorityQueue<Integer> nums = new PriorityQueue<>(List.of(40, 10, 30, 20));
17 System.out.println("smallest first: " + nums.poll() + ", " + nums.poll());
18 }
19}
Terminal
D:\java-practice> java Main.java
Treating Seema (accident) [level 1]
Treating Rafiq (fracture) [level 2]
Treating Mohan (fever) [level 4]
Treating Lata (cough) [level 5]
smallest first: 10, 20
💡 Concept in shortPriorityQueue always gives the highest-priority element on poll(). By default that is the smallest; pass a Comparator to decide priority (more in Module 16).
Module 15Hands-on

Code Lab: Try It Yourself

Main.java
Output of the starter code
D:\java-practice> java Main.java
To do (2): [Pay electricity bill, Book Ranchi-Delhi train]
Done: [Recharge DTH, Buy books]
print -> Pay electricity bill
print -> Book Ranchi-Delhi train
Change the code, then run it on your computer: ⬇ Download → open a terminal in that folder → java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).
Your tasks
  1. Add priorities: use a PriorityQueue of records Task(String name, int priority)
  2. Prevent adding the same task twice (use a Set check)
  3. Print the to-do list sorted alphabetically
  4. Mark a task done by its index safely (check the size)
PracticePractice 1 of 10 · Easy

Class Attendance List

EasyScenario. A teacher marks present students in a growing list.
💡 Concept used: ArrayList add, size, contains, remove.

Your tasks

  1. Add 5 names
  2. Remove one who left early
  3. Check whether a student is present
  4. Print count
🏢 Used in real projects: Attendance apps keep lists that grow and shrink during the day.
Attendance.java  JAVA
1import java.util.*;
2
3public class Attendance {
4 public static void main(String[] args) {
5 List<String> present = new ArrayList<>();
6 present.add("Aditi"); present.add("Bablu"); present.add("Chanda"); present.add("Deepak"); present.add("Esha");
7 present.remove("Bablu");
8 System.out.println("Present (" + present.size() + "): " + present);
9 System.out.println("Is Deepak present? " + present.contains("Deepak"));
10 System.out.println("Is Bablu present? " + present.contains("Bablu"));
11 }
12}
PracticePractice 2 of 10 · Easy

Marks List Statistics

EasyScenario. Marks are entered one by one; compute total, average and highest.
💡 Concept used: List<Integer> with autoboxing and Collections.max/min.

Your tasks

  1. Add marks to a List<Integer>
  2. Sum with for-each
  3. Collections.max and min
  4. Print the average
🏢 Used in real projects: Dashboards compute stats from lists returned by a database.
MarksStats.java  JAVA
1import java.util.*;
2
3public class MarksStats {
4 public static void main(String[] args) {
5 List<Integer> marks = new ArrayList<>(List.of(67, 88, 45, 92, 73, 59));
6 int sum = 0;
7 for (int m : marks) sum += m;
8 System.out.println("Marks: " + marks);
9 System.out.printf("Total %d, average %.2f%n", sum, sum / (double) marks.size());
10 System.out.println("Highest " + Collections.max(marks) + ", lowest " + Collections.min(marks));
11 Collections.sort(marks);
12 System.out.println("Sorted: " + marks);
13 }
14}
PracticePractice 3 of 10 · Easy

Remove Duplicate Emails

EasyScenario. A newsletter sign-up list has repeated emails in different cases.
💡 Concept used: A Set removes duplicates; normalise case first.

Your tasks

  1. Lower-case each email
  2. Add to a LinkedHashSet
  3. Print unique count and list
🏢 Used in real projects: Mailing tools de-duplicate contacts before sending.
UniqueEmails.java  JAVA
1import java.util.*;
2
3public class UniqueEmails {
4 public static void main(String[] args) {
5 String[] signups = {"riya@gmail.com", "Aman@yahoo.in", "RIYA@gmail.com", "zoya@outlook.com", "aman@yahoo.in"};
6 Set<String> unique = new LinkedHashSet<>();
7 for (String e : signups) unique.add(e.toLowerCase());
8 System.out.println(signups.length + " sign-ups, " + unique.size() + " unique:");
9 for (String e : unique) System.out.println(" " + e);
10 }
11}
PracticePractice 4 of 10 · Easy

Wishlist and Cart

EasyScenario. An e-commerce app moves items from a wishlist to a cart and removes out-of-stock items.
💡 Concept used: Moving objects between two lists; removeIf with a condition.

Your tasks

  1. Wishlist and cart lists of records
  2. Move an item by name
  3. removeIf out of stock
  4. Print both lists and cart total
🏢 Used in real projects: Shopping apps constantly move objects between lists.
Wishlist.java  JAVA
1import java.util.*;
2
3record Product(String name, int price, boolean inStock) { }
4
5public class Wishlist {
6 public static void main(String[] args) {
7 List<Product> wish = new ArrayList<>(List.of(new Product("Shoes", 1799, true), new Product("Watch", 2499, false), new Product("Bag", 999, true)));
8 List<Product> cart = new ArrayList<>();
9 for (String want : new String[]{"Shoes", "Watch"}) {
10 for (Product p : wish) if (p.name().equals(want)) { cart.add(p); break; }
11 }
12 wish.removeAll(cart);
13 cart.removeIf(p -> !p.inStock());
14 int total = 0;
15 for (Product p : cart) total += p.price();
16 System.out.println("Wishlist: " + wish);
17 System.out.println("Cart: " + cart + " total Rs " + total);
18 }
19}
PracticePractice 5 of 10 · Easy

Browser History with Deque

EasyScenario. A browser keeps back and forward history.
💡 Concept used: Two stacks (ArrayDeque push/pop) implement back and forward.

Your tasks

  1. visit(url) pushes current to back and clears forward
  2. back() and forward()
  3. Simulate a session
🏢 Used in real projects: Browsers, editors (undo/redo) and navigation in apps use stacks.
Browser.java  JAVA
1import java.util.*;
2
3public class Browser {
4 static Deque<String> back = new ArrayDeque<>(), fwd = new ArrayDeque<>();
5 static String current = "home";
6 static void visit(String u) { back.push(current); current = u; fwd.clear(); System.out.println("visit " + current); }
7 static void goBack() { if (!back.isEmpty()) { fwd.push(current); current = back.pop(); } System.out.println("back " + current); }
8 static void goForward() { if (!fwd.isEmpty()) { back.push(current); current = fwd.pop(); } System.out.println("forward " + current); }
9
10 public static void main(String[] args) {
11 visit("jharkhand.gov.in"); visit("results"); visit("class-10");
12 goBack(); goBack(); goForward();
13 visit("admit-card");
14 goForward();
15 System.out.println("Back stack: " + back);
16 }
17}
PracticePractice 6 of 10 · Medium

Hospital Token System

MediumScenario. RIMS OPD: normal patients wait in a queue; emergency patients jump ahead by severity.
💡 Concept used: Queue for normal FIFO + PriorityQueue for emergencies; always serve emergency first.

Your tasks

  1. Queue<String> normal
  2. PriorityQueue<record Emergency> by severity
  3. serveNext() prefers emergencies
  4. Simulate arrivals and serving
🏢 Used in real projects: Hospital, bank and service-centre token systems combine queues and priority queues.
Opd.java  JAVA
1import java.util.*;
2
3record Emergency(String name, int severity) { }
4
5public class Opd {
6 static Queue<String> normal = new ArrayDeque<>();
7 static PriorityQueue<Emergency> urgent = new PriorityQueue<>(Comparator.comparingInt(Emergency::severity));
8 static int token = 100;
9
10 static void arrive(String n) { normal.offer("T" + (++token) + " " + n); }
11 static void serveNext() {
12 if (!urgent.isEmpty()) System.out.println("EMERGENCY -> " + urgent.poll().name());
13 else if (!normal.isEmpty()) System.out.println("Counter -> " + normal.poll());
14 else System.out.println("No patients");
15 }
16
17 public static void main(String[] args) {
18 arrive("Mohan"); arrive("Geeta"); arrive("Imran");
19 serveNext();
20 urgent.add(new Emergency("Accident case", 1));
21 urgent.add(new Emergency("High fever child", 3));
22 serveNext(); serveNext(); serveNext(); serveNext(); serveNext();
23 }
24}
PracticePractice 7 of 10 · Medium

Common Friends with Sets

MediumScenario. A social app suggests friends: mutual friends and "people you may know".
💡 Concept used: Set intersection (retainAll) and difference (removeAll) on copies.

Your tasks

  1. friends of Aman and of Riya as sets
  2. Mutual friends
  3. Suggestions for Aman: Riya's friends minus Aman's and himself
  4. Print sorted
🏢 Used in real projects: Facebook/Instagram-style suggestions start from set operations.
Friends.java  JAVA
1import java.util.*;
2
3public class Friends {
4 public static void main(String[] args) {
5 Set<String> aman = new TreeSet<>(List.of("Riya", "Dev", "Kunal", "Sana"));
6 Set<String> riya = new TreeSet<>(List.of("Aman", "Dev", "Sana", "Tara", "Vikas"));
7 Set<String> mutual = new TreeSet<>(aman);
8 mutual.retainAll(riya);
9 Set<String> suggest = new TreeSet<>(riya);
10 suggest.removeAll(aman);
11 suggest.remove("Aman");
12 System.out.println("Mutual friends: " + mutual + " (" + mutual.size() + ")");
13 System.out.println("People Aman may know: " + suggest);
14 }
15}
PracticePractice 8 of 10 · Medium

Library Waitlist with Iterator

MediumScenario. A library keeps a waitlist per book; members who cancel are removed while scanning; the first remaining member gets the book.
💡 Concept used: Safe removal with Iterator; List of records; Queue built from a List.

Your tasks

  1. List of Request records (member, cancelled)
  2. Iterator removes cancelled ones
  3. Convert remaining to a Queue
  4. Allot copies in order
🏢 Used in real projects: Waitlists (books, trains, courses) clean and serve queues exactly like this.
Waitlist.java  JAVA
1import java.util.*;
2
3record Request(String member, boolean cancelled) { }
4
5public class Waitlist {
6 public static void main(String[] args) {
7 List<Request> list = new ArrayList<>(List.of(new Request("Asha", false), new Request("Binod", true), new Request("Chetna", false), new Request("Dilip", true), new Request("Ekta", false)));
8 Iterator<Request> it = list.iterator();
9 while (it.hasNext()) {
10 Request r = it.next();
11 if (r.cancelled()) {
12 System.out.println("Removed " + r.member());
13 it.remove();
14 }
15 }
16 Queue<Request> q = new ArrayDeque<>(list);
17 int copies = 2;
18 while (copies-- > 0 && !q.isEmpty()) System.out.println("Allotted to " + q.poll().member());
19 System.out.println("Still waiting: " + q.size());
20 }
21}
PracticePractice 9 of 10 · Hard

Exam Seating Planner

HardScenario. Allot exam seats: unique roll numbers sorted, shuffled with a seed so friends do not sit together, then filled room by room.
💡 Concept used: TreeSet for unique sorted rolls, ArrayList + Collections.shuffle(Random), subList for chunks.

Your tasks

  1. Remove duplicate roll numbers with TreeSet
  2. Copy to a List and shuffle with seed 7
  3. Split into rooms of 4 with subList
  4. Print the room charts
🏢 Used in real projects: Exam and event management systems allocate seats with these collection steps.
Seating.java  JAVA
1import java.util.*;
2
3public class Seating {
4 public static void main(String[] args) {
5 int[] raw = {1203, 1187, 1250, 1203, 1199, 1222, 1187, 1240, 1211, 1233};
6 Set<Integer> rolls = new TreeSet<>();
7 for (int r : raw) rolls.add(r);
8 System.out.println("Unique rolls (" + rolls.size() + "): " + rolls);
9 List<Integer> order = new ArrayList<>(rolls);
10 Collections.shuffle(order, new Random(7));
11 int room = 101;
12 for (int i = 0; i < order.size(); i += 4) {
13 List<Integer> chunk = order.subList(i, Math.min(i + 4, order.size()));
14 System.out.println("Room " + room++ + ": " + chunk);
15 }
16 }
17}
PracticePractice 10 of 10 · Hard

Print Job Scheduler

HardScenario. An office printer: urgent jobs first, then by page count (smallest first); jobs from the same file are not queued twice.
💡 Concept used: PriorityQueue with a multi-level Comparator plus a HashSet to block duplicates.

Your tasks

  1. record Job(file, pages, urgent)
  2. Comparator: urgent first, then fewer pages
  3. HashSet of file names to reject repeats
  4. Print the print order and total pages
🏢 Used in real projects: Operating systems and job servers schedule work with priority queues.
PrintQueue.java  JAVA
1import java.util.*;
2
3record Job(String file, int pages, boolean urgent) { }
4
5public class PrintQueue {
6 public static void main(String[] args) {
7 Comparator<Job> order = Comparator.comparing((Job j) -> !j.urgent()).thenComparingInt(Job::pages);
8 PriorityQueue<Job> pq = new PriorityQueue<>(order);
9 Set<String> queued = new HashSet<>();
10 Job[] incoming = {new Job("salary.pdf", 12, false), new Job("notice.docx", 1, true), new Job("report.pdf", 40, false),
11 new Job("salary.pdf", 12, false), new Job("admit-card.pdf", 2, true), new Job("menu.png", 1, false)};
12 for (Job j : incoming) {
13 if (queued.add(j.file())) pq.add(j);
14 else System.out.println("Skipped duplicate " + j.file());
15 }
16 int pages = 0;
17 while (!pq.isEmpty()) {
18 Job j = pq.poll();
19 pages += j.pages();
20 System.out.printf("%-15s %3d pages %s%n", j.file(), j.pages(), j.urgent() ? "URGENT" : "");
21 }
22 System.out.println("Total pages printed: " + pages);
23 }
24}
Module 15Recap

Module 15 Recap & Quiz

What you learned

  • 1Collections grow and shrink; they store objects (List<Integer>)
  • 2ArrayList: ordered, duplicates, index access: add, get, set, remove, size
  • 3Remove while looping with Iterator or removeIf
  • 4HashSet (fast), LinkedHashSet (order), TreeSet (sorted): no duplicates
  • 5Queue (FIFO): offer, poll, peek; Deque as stack: push, pop
  • 6PriorityQueue: most important first, with a Comparator

Quick quiz

Which allows duplicates and keeps order?

Lists keep order and allow duplicates.

set.add("x") when "x" is already there returns...

add returns false for a duplicate.

Which serves first-come first-served?

Queue is FIFO.
MODULE 16

Collections II: Maps and Sorting

⏱ 5 hours10 practice examplesStep-through animationsCode Lab

You will learn

  • Map: key -> value pairs (HashMap, LinkedHashMap, TreeMap)
  • put, get, getOrDefault, containsKey, remove
  • Looping with entrySet; counting with merge
  • Sorting objects: Comparable (natural order)
  • Comparator: any order, multi-level sorting

You will build

  • A word and vote counter
  • A phone book and product catalogue
  • Sorted merit lists and price filters
Mapmap.put(k, v)Comparator.comparing(...)
Module 16Real-world use

Where Is This Used in Real Projects?

mapslook up by key📞Phone bookname -> number🛒Cataloguecode -> product🗳Electionsparty -> votes🔑Loginsusername -> user🌐Cachesurl -> page📈Reportsmonth -> sales

Real projects that use this

  • Look up a product by barcode instantly, without looping through a list
  • Count things: words in a text, orders per city, votes per candidate
  • JSON objects map directly to Map<String, Object>
  • Sorting by price, rating or date is done with Comparators
Module 16The idea

A Map Connects Keys to Values

KEY (unique)VALUE"Ranchi"1.5 M"Jamshedpur"1.4 M"Dhanbad"1.2 M"Bokaro"0.6 Mpopulation.get("Dhanbad") -> 1.2 M
💡 Concept in shortA Map stores key -> value pairs. Keys are unique; putting an existing key replaces its value. You find a value by its key, like a word in a dictionary.
ClassOrder of keys
HashMapno fixed order (fastest)
LinkedHashMapinsertion order
TreeMapsorted by key
RememberMap<String, Integer>: first type = key, second = value.
Module 16HashMap

HashMap Basics: put, get, remove

Main.java  JAVA
1import java.util.*;
2
3public class Main {
4 public static void main(String[] args) {
5 Map<String, String> phone = new HashMap<>();
6 phone.put("Riya", "98350 11223");
7 phone.put("Aman", "70040 55667");
8 phone.put("Sana", "62000 88990");
9 phone.put("Aman", "70040 00000"); // same key: value replaced
10
11 System.out.println("Aman: " + phone.get("Aman"));
12 System.out.println("Ravi: " + phone.get("Ravi")); // missing -> null
13 System.out.println("Ravi: " + phone.getOrDefault("Ravi", "not saved"));
14 System.out.println("Has Sana? " + phone.containsKey("Sana"));
15 phone.remove("Riya");
16 System.out.println(phone.size() + " contacts, names " + new TreeSet<>(phone.keySet()));
17 }
18}
Terminal
D:\java-practice> java Main.java
Aman: 70040 00000
Ravi: null
Ravi: not saved
Has Sana? true
2 contacts, names [Aman, Sana]
💡 Concept in shortput(k, v) adds or replaces, get(k) returns the value or null, getOrDefault avoids null, containsKey checks, keySet() and values() give the parts.
RememberMap lookup by key is almost instant even with millions of entries (hashing). Searching a List is much slower.
Module 16Animation

Watch a Map Change

Map<String, Integer> orders

"Ranchi"12
"Dhanbad"7
Map<String, Integer> orders = new LinkedHashMap<>(Map.of(...));
Starting value.
💡 Concept in shortmerge(key, 1, Integer::sum) is the standard way to count: it inserts 1 for a new key or adds 1 to the existing value.
MethodDoes
putIfAbsent(k, v)only if missing
merge(k, v, f)combine values
computeIfAbsentcreate value on demand
Module 16Loop a map

Looping Over a Map with entrySet()

Main.java  JAVA
1import java.util.*;
2
3public class Main {
4 public static void main(String[] args) {
5 Map<String, Integer> sales = new TreeMap<>(); // sorted by key
6 sales.put("Mar", 41000);
7 sales.put("Jan", 52000);
8 sales.put("Feb", 38500);
9
10 int total = 0;
11 for (Map.Entry<String, Integer> e : sales.entrySet()) {
12 System.out.printf("%s Rs %,7d %s%n", e.getKey(), e.getValue(), "#".repeat(e.getValue() / 5000));
13 total += e.getValue();
14 }
15 System.out.printf("Total Rs %,d%n", total);
16
17 sales.forEach((month, amt) -> {
18 if (amt > 40000) System.out.println(month + " crossed target");
19 });
20 }
21}
Terminal
D:\java-practice> java Main.java
Feb Rs 38,500 #######
Jan Rs 52,000 ##########
Mar Rs 41,000 ########
Total Rs 131,500
Jan crossed target
Mar crossed target
💡 Concept in shortentrySet() gives every key-value pair as a Map.Entry with getKey() and getValue(). forEach((k, v) -> ...) is the short lambda version.
Common mistakeTreeMap sorts String keys alphabetically, so "Feb" comes before "Jan". Use a Month enum or LinkedHashMap to keep calendar order.
Module 16Counting

Step Through: Counting Votes with merge()

The counting pattern: one line inside the loop builds a frequency table. Watch count grow.

Main.java  JAVA
1import java.util.*;
2
3public class Main {
4 public static void main(String[] args) {
5 String[] votes = {"Lotus", "Hand", "Lotus", "Bow", "Lotus", "Hand"};
6 Map<String, Integer> count = new TreeMap<>();
7 for (String v : votes) {
8 count.merge(v, 1, Integer::sum);
9 }
10 System.out.println(count);
11 }
12}
Output
Module 16Comparable

Comparable: Teach Your Class Its Natural Order

Main.java  JAVA
1import java.util.*;
2
3class Student implements Comparable<Student> {
4 String name; int marks;
5 Student(String n, int m) { name = n; marks = m; }
6
7 @Override
8 public int compareTo(Student other) {
9 return Integer.compare(other.marks, this.marks); // higher marks first
10 }
11 public String toString() { return name + "(" + marks + ")"; }
12}
13
14public class Main {
15 public static void main(String[] args) {
16 List<Student> list = new ArrayList<>(List.of(new Student("Aman", 78), new Student("Bina", 95), new Student("Chirag", 61), new Student("Diya", 88)));
17 Collections.sort(list); // uses compareTo
18 System.out.println("Merit list: " + list);
19 TreeSet<Student> top = new TreeSet<>(list);
20 System.out.println("Topper: " + top.first());
21 }
22}
Terminal
D:\java-practice> java Main.java
Merit list: [Bina(95), Diya(88), Aman(78), Chirag(61)]
Topper: Bina(95)
💡 Concept in shortcompareTo returns negative (this comes first), 0 (equal) or positive (other comes first). Collections.sort, TreeSet and TreeMap use it automatically.
RememberUse Integer.compare(a, b) rather than a - b, which can overflow.
Module 16Comparator

Comparator: Sort Any Way You Like

Main.java  JAVA
1import java.util.*;
2
3record Phone(String model, int price, double rating, int ramGb) { }
4
5public class Main {
6 public static void main(String[] args) {
7 List<Phone> phones = new ArrayList<>(List.of(
8 new Phone("Redmi 13", 11999, 4.2, 6), new Phone("Galaxy M35", 17999, 4.3, 8),
9 new Phone("Moto G64", 14999, 4.3, 8), new Phone("Nord CE4", 24999, 4.5, 8)));
10
11 phones.sort(Comparator.comparingInt(Phone::price));
12 System.out.println("Price low-high: " + names(phones));
13
14 phones.sort(Comparator.comparingDouble(Phone::rating).reversed()
15 .thenComparingInt(Phone::price));
16 System.out.println("Best rated, then cheaper: " + names(phones));
17
18 phones.sort((a, b) -> a.model().compareTo(b.model()));
19 System.out.println("A-Z: " + names(phones));
20 }
21 static List<String> names(List<Phone> l) {
22 List<String> n = new ArrayList<>();
23 for (Phone p : l) n.add(p.model());
24 return n;
25 }
26}
Terminal
D:\java-practice> java Main.java
Price low-high: [Redmi 13, Moto G64, Galaxy M35, Nord CE4]
Best rated, then cheaper: [Nord CE4, Moto G64, Galaxy M35, Redmi 13]
A-Z: [Galaxy M35, Moto G64, Nord CE4, Redmi 13]
💡 Concept in shortA Comparator is a separate sorting rule, so one class can be sorted many ways. Build it with Comparator.comparing(...), flip with .reversed(), and break ties with .thenComparing(...).
RememberThis is exactly what "Sort by: Price | Rating | Newest" on a shopping site does.
Module 16Choose

Which Collection Should I Use?

QuestionAnswer
Need key -> value lookup?HashMap (sorted keys: TreeMap)
Ordered items, duplicates OK?ArrayList
Unique items?HashSet / TreeSet
First come first served?ArrayDeque
Most urgent first?PriorityQueue
Undo / back history?ArrayDeque as stack
Group items by category?Map<K, List<V>>
💡 Concept in shortPick the collection by the question you ask most often: "what is at position 3?" (List), "is X there?" (Set), "what belongs to key K?" (Map), "who is next?" (Queue).
📄 Grouping pattern (file on disk)TXT
1Map<String, List<String>> byCity = new TreeMap<>();
2byCity.computeIfAbsent("Ranchi", k -> new ArrayList<>())
3 .add("Aditi");
Module 16Hands-on

Code Lab: Try It Yourself

Main.java
Output of the starter code
D:\java-practice> java Main.java
{and=2, easy=1, fun=1, is=2, java=2, powerful=1}
Most used: and
Change the code, then run it on your computer: ⬇ Download → open a terminal in that folder → java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).
Your tasks
  1. Ignore case and punctuation before counting
  2. Print the top 3 words with counts
  3. Group words by their length into Map<Integer, List<String>>
  4. Count letters instead of words
PracticePractice 1 of 10 · Easy

Phone Book

EasyScenario. A small shop saves customer numbers by name.
💡 Concept used: HashMap put/get/containsKey/getOrDefault.

Your tasks

  1. Add 4 contacts
  2. Look up two names (one missing)
  3. Update one number
  4. Print all in sorted order
🏢 Used in real projects: Contact apps and CRMs store people in maps keyed by id or name.
PhoneBook.java  JAVA
1import java.util.*;
2
3public class PhoneBook {
4 public static void main(String[] args) {
5 Map<String, String> book = new HashMap<>();
6 book.put("Mahto Electricals", "98350 12345");
7 book.put("Gupta Sweets", "70040 22334");
8 book.put("Lakra Tailors", "62039 44556");
9 book.put("Singh Medicals", "91234 99887");
10 System.out.println(book.getOrDefault("Gupta Sweets", "not found"));
11 System.out.println(book.getOrDefault("Roy Hardware", "not found"));
12 book.put("Gupta Sweets", "70040 00001");
13 for (Map.Entry<String, String> e : new TreeMap<>(book).entrySet()) System.out.println(e.getKey() + " : " + e.getValue());
14 }
15}
PracticePractice 2 of 10 · Easy

Word Counter

EasyScenario. Count how many times each word appears in a sentence.
💡 Concept used: merge(word, 1, Integer::sum) builds a frequency map.

Your tasks

  1. Split the text
  2. Count with merge
  3. Print with TreeMap (sorted)
🏢 Used in real projects: Search engines, hashtags and analytics all start with counting.
WordCount.java  JAVA
1import java.util.*;
2
3public class WordCount {
4 public static void main(String[] args) {
5 String s = "the river subarnarekha flows through ranchi and the river is beautiful";
6 Map<String, Integer> c = new TreeMap<>();
7 for (String w : s.split(" ")) c.merge(w, 1, Integer::sum);
8 System.out.println(c);
9 System.out.println("Distinct words: " + c.size());
10 }
11}
PracticePractice 3 of 10 · Easy

Price Catalogue Lookup

EasyScenario. A billing counter finds prices by product code.
💡 Concept used: Map<String, Double> for instant lookup; compute a bill from codes.

Your tasks

  1. Catalogue of 5 codes
  2. Bill a list of scanned codes
  3. Report unknown codes
🏢 Used in real projects: POS systems look up barcodes in maps or databases.
Catalogue.java  JAVA
1import java.util.*;
2
3public class Catalogue {
4 public static void main(String[] args) {
5 Map<String, Double> price = Map.of("P01", 45.0, "P02", 120.0, "P03", 15.5, "P04", 299.0, "P05", 60.0);
6 String[] scanned = {"P02", "P03", "P03", "P09", "P05"};
7 double bill = 0;
8 for (String code : scanned) {
9 Double p = price.get(code);
10 if (p == null) System.out.println("Unknown code " + code);
11 else bill += p;
12 }
13 System.out.println("Bill: Rs " + bill);
14 }
15}
PracticePractice 4 of 10 · Easy

Election Vote Counter

EasyScenario. Count votes per candidate and declare the winner.
💡 Concept used: merge for counting + finding the max entry.

Your tasks

  1. Count votes in a LinkedHashMap
  2. Find the winner and margin
  3. Print a bar chart
🏢 Used in real projects: School elections, polls and surveys tally with maps.
Election.java  JAVA
1import java.util.*;
2
3public class Election {
4 public static void main(String[] args) {
5 String[] votes = {"Meena", "Ravi", "Meena", "Arjun", "Ravi", "Meena", "Arjun", "Meena", "Ravi"};
6 Map<String, Integer> c = new LinkedHashMap<>();
7 for (String v : votes) c.merge(v, 1, Integer::sum);
8 String win = null; int best = -1, second = -1;
9 for (Map.Entry<String, Integer> e : c.entrySet()) {
10 System.out.printf("%-6s %s %d%n", e.getKey(), "#".repeat(e.getValue()), e.getValue());
11 if (e.getValue() > best) { second = best; best = e.getValue(); win = e.getKey(); }
12 else if (e.getValue() > second) second = e.getValue();
13 }
14 System.out.println("Winner: " + win + " by " + (best - second) + " votes");
15 }
16}
PracticePractice 5 of 10 · Easy

Sort Products Many Ways

EasyScenario. A shopping app offers sort by price, by rating and by name.
💡 Concept used: Comparator.comparing with reversed and thenComparing.

Your tasks

  1. record Product(name, price, rating)
  2. Sort by price ascending
  3. Sort by rating descending then price
  4. Sort by name
🏢 Used in real projects: "Sort by" dropdowns on every e-commerce site.
SortBy.java  JAVA
1import java.util.*;
2
3record Product(String name, int price, double rating) { }
4
5public class SortBy {
6 public static void main(String[] args) {
7 List<Product> l = new ArrayList<>(List.of(new Product("Kurta", 899, 4.1), new Product("Saree", 2499, 4.6), new Product("Jacket", 1999, 4.1), new Product("Shawl", 699, 4.4)));
8 l.sort(Comparator.comparingInt(Product::price));
9 System.out.println("Price : " + l);
10 l.sort(Comparator.comparingDouble(Product::rating).reversed().thenComparingInt(Product::price));
11 System.out.println("Rating : " + l);
12 l.sort(Comparator.comparing(Product::name));
13 System.out.println("Name : " + l);
14 }
15}
PracticePractice 6 of 10 · Medium

Group Students by City

MediumScenario. A coaching institute groups students by home city for transport routes.
💡 Concept used: Map<String, List<String>> with computeIfAbsent: the grouping pattern.

Your tasks

  1. Records Student(name, city)
  2. computeIfAbsent(city, ...).add(name)
  3. Print each city with count and names
  4. Sort names inside each group
🏢 Used in real projects: Reports grouped by category, city or month use exactly this pattern.
Routes.java  JAVA
1import java.util.*;
2
3record Student(String name, String city) { }
4
5public class Routes {
6 public static void main(String[] args) {
7 List<Student> all = List.of(new Student("Aman", "Ranchi"), new Student("Pooja", "Ramgarh"), new Student("Imran", "Ranchi"), new Student("Kavya", "Khunti"), new Student("Bittu", "Ramgarh"), new Student("Asha", "Ranchi"));
8 Map<String, List<String>> byCity = new TreeMap<>();
9 for (Student s : all) byCity.computeIfAbsent(s.city(), k -> new ArrayList<>()).add(s.name());
10 for (Map.Entry<String, List<String>> e : byCity.entrySet()) {
11 Collections.sort(e.getValue());
12 System.out.println(e.getKey() + " (" + e.getValue().size() + "): " + e.getValue());
13 }
14 }
15}
PracticePractice 7 of 10 · Medium

Inventory Stock Manager

MediumScenario. A kirana store updates stock on purchase and sale and warns on low stock.
💡 Concept used: Updating map values with merge (add/subtract), getOrDefault and a threshold check.

Your tasks

  1. Map item -> qty
  2. purchase(item, q) and sell(item, q) (refuse if not enough)
  3. Low-stock report (< 5)
🏢 Used in real projects: Inventory systems keep item -> quantity maps (or database tables).
Stock.java  JAVA
1import java.util.*;
2
3public class Stock {
4 static Map<String, Integer> stock = new TreeMap<>();
5 static void purchase(String item, int q) { stock.merge(item, q, Integer::sum); }
6 static void sell(String item, int q) {
7 int have = stock.getOrDefault(item, 0);
8 if (q > have) { System.out.println("Cannot sell " + q + " " + item + " (have " + have + ")"); return; }
9 stock.put(item, have - q);
10 }
11 public static void main(String[] args) {
12 purchase("Rice kg", 50); purchase("Sugar kg", 20); purchase("Salt pkt", 10);
13 sell("Rice kg", 47); sell("Sugar kg", 8); sell("Salt pkt", 12); sell("Tea pkt", 1);
14 purchase("Sugar kg", 5);
15 System.out.println("Stock: " + stock);
16 stock.forEach((k, v) -> { if (v < 5) System.out.println("LOW: " + k + " only " + v); });
17 }
18}
PracticePractice 8 of 10 · Medium

Merit List with Tie-Breaking

MediumScenario. Board results: rank by total, ties broken by Maths marks, then by name.
💡 Concept used: Multi-level Comparator, then assign ranks with equal ranks for exact ties.

Your tasks

  1. record Result(name, total, maths)
  2. Comparator: total desc, maths desc, name asc
  3. Assign rank (same rank for same total and maths)
  4. Print the merit list
🏢 Used in real projects: JEE/NEET and board result systems rank with tie-break rules like these.
MeritTie.java  JAVA
1import java.util.*;
2
3record Result(String name, int total, int maths) { }
4
5public class MeritTie {
6 public static void main(String[] args) {
7 List<Result> r = new ArrayList<>(List.of(new Result("Asha", 472, 95), new Result("Binod", 488, 99), new Result("Chetan", 472, 98),
8 new Result("Diya", 488, 99), new Result("Eshan", 455, 90)));
9 r.sort(Comparator.comparingInt(Result::total).reversed()
10 .thenComparing(Comparator.comparingInt(Result::maths).reversed())
11 .thenComparing(Result::name));
12 int rank = 0;
13 for (int i = 0; i < r.size(); i++) {
14 Result x = r.get(i);
15 boolean tie = i > 0 && x.total() == r.get(i - 1).total() && x.maths() == r.get(i - 1).maths();
16 if (!tie) rank = i + 1;
17 System.out.printf("%d. %-7s %d (maths %d)%n", rank, x.name(), x.total(), x.maths());
18 }
19 }
20}
PracticePractice 9 of 10 · Hard

Train Reservation Chart

HardScenario. Build a coach-wise reservation chart: Map<coach, TreeMap<seat, passenger>>; book, cancel and print.
💡 Concept used: Nested maps, TreeMap for sorted seats, putIfAbsent to prevent double booking.

Your tasks

  1. book(coach, seat, name) refuses taken seats
  2. cancel(coach, seat)
  3. Print chart coach by coach in seat order
  4. Count occupancy per coach
🏢 Used in real projects: Reservation systems (rail, bus, cinema) store seat maps per coach or screen.
Chart.java  JAVA
1import java.util.*;
2
3public class Chart {
4 static Map<String, TreeMap<Integer, String>> chart = new TreeMap<>();
5 static void book(String coach, int seat, String name) {
6 String old = chart.computeIfAbsent(coach, k -> new TreeMap<>()).putIfAbsent(seat, name);
7 System.out.println(old == null ? "Booked " + coach + "-" + seat + " " + name : "X " + coach + "-" + seat + " taken by " + old);
8 }
9 static void cancel(String coach, int seat) {
10 String n = chart.getOrDefault(coach, new TreeMap<>()).remove(seat);
11 System.out.println(n == null ? "Nothing to cancel" : "Cancelled " + coach + "-" + seat + " (" + n + ")");
12 }
13 public static void main(String[] args) {
14 book("S2", 14, "Anil"); book("S1", 3, "Rekha"); book("S2", 9, "Faizan"); book("S2", 14, "Mona"); book("B1", 22, "Kiran");
15 cancel("S2", 9); book("S2", 9, "Mona");
16 for (Map.Entry<String, TreeMap<Integer, String>> c : chart.entrySet()) {
17 System.out.println("Coach " + c.getKey() + " (" + c.getValue().size() + " booked): " + c.getValue());
18 }
19 }
20}
PracticePractice 10 of 10 · Hard

Sales Report by City and Month

HardScenario. A distributor's orders are summarised: total per city, best month per city, and top 2 cities.
💡 Concept used: Nested Map<String, Map<String, Integer>>, merge for sums, and sorting map entries by value.

Your tasks

  1. Orders as records (city, month, amount)
  2. Total per city with merge
  3. Per-city per-month map; best month
  4. Top 2 cities by sales
🏢 Used in real projects: Business dashboards aggregate orders exactly like this (Streams make it shorter: Module 17).
SalesReport.java  JAVA
1import java.util.*;
2
3record Order(String city, String month, int amount) { }
4
5public class SalesReport {
6 public static void main(String[] args) {
7 List<Order> orders = List.of(new Order("Ranchi", "Jan", 42000), new Order("Dhanbad", "Jan", 31000), new Order("Ranchi", "Feb", 51000),
8 new Order("Bokaro", "Feb", 18000), new Order("Dhanbad", "Feb", 36000), new Order("Ranchi", "Jan", 9000), new Order("Bokaro", "Jan", 22000));
9 Map<String, Integer> total = new TreeMap<>();
10 Map<String, Map<String, Integer>> byMonth = new TreeMap<>();
11 for (Order o : orders) {
12 total.merge(o.city(), o.amount(), Integer::sum);
13 byMonth.computeIfAbsent(o.city(), k -> new TreeMap<>()).merge(o.month(), o.amount(), Integer::sum);
14 }
15 for (String city : total.keySet()) {
16 Map.Entry<String, Integer> best = Collections.max(byMonth.get(city).entrySet(), Map.Entry.comparingByValue());
17 System.out.printf("%-8s Rs %,7d best %s (Rs %,d)%n", city, total.get(city), best.getKey(), best.getValue());
18 }
19 List<Map.Entry<String, Integer>> rank = new ArrayList<>(total.entrySet());
20 rank.sort(Map.Entry.<String, Integer>comparingByValue().reversed());
21 System.out.println("Top 2: " + rank.subList(0, 2));
22 }
23}
Module 16Recap

Module 16 Recap & Quiz

What you learned

  • 1Map = unique keys -> values; HashMap, LinkedHashMap, TreeMap
  • 2put, get, getOrDefault, containsKey, remove, keySet, values
  • 3Loop with entrySet() or forEach((k, v) -> ...)
  • 4Count with merge(k, 1, Integer::sum); group with computeIfAbsent
  • 5Comparable: natural order via compareTo
  • 6Comparator: comparing, reversed, thenComparing

Quick quiz

map.put("A", 1); map.put("A", 2); map size?

Same key replaces the value.

map.get("missing") returns...

Use getOrDefault to avoid null.

Which map keeps keys sorted?

TreeMap sorts by key.
MODULE 17

Lambdas and the Stream API

⏱ 5 hours10 practice examplesStep-through animationsCode Lab

You will learn

  • Lambda expressions: functions as values
  • Built-in functional interfaces: Predicate, Function, Consumer, Supplier
  • Method references (Class::method)
  • Streams: filter, map, sorted, limit, collect
  • Reductions and grouping: sum, average, count, groupingBy

You will build

  • Order analytics in a few lines
  • Search and filter like an e-commerce site
  • Class result dashboards
->x -&gt; x * 2.filter().map().collect()
Module 17Real-world use

Where Is This Used in Real Projects?

streamsmodern, short, readable📊Dashboardssum, average🔍Search filtersfilter by price📈ReportsgroupingBy city📋Data cleaningmap, distinct🌱Spring Bootlambdas everywhere⚙Event handlersbutton.onClick(e -> ...)

Real projects that use this

  • Modern Java code (Java 8+) uses lambdas and streams in almost every class
  • Filtering products by price and rating is one stream pipeline
  • Reports like "total sales per city" become one groupingBy
  • Interviews for Java jobs always include stream questions
Module 17Lambdas

A Lambda Is a Short, Unnamed Method

(a, b)parameters
-&gt; arrow
a + bbody (result)
Old wayLambda
new Comparator<P>() { public int compare(P a, P b) { return a.price - b.price; } }(a, b) -> a.price - b.price
new Runnable() { public void run() { System.out.println("Hi"); } }() -> System.out.println("Hi")
💡 Concept in shortA lambda (params) -> expression is a compact way to pass behaviour as a value. It implements a functional interface (one abstract method, Module 12).
  1. 1
    One parameter: brackets optional x -> x * 2
  2. 2
    No parameters: () -> 42
  3. 3
    Several statements: use { ...; return r; }
  4. 4
    Types are inferred: (int a, int b) is optional
Module 17Built-in interfaces

Predicate, Function, Consumer, Supplier

Main.java  JAVA
1import java.util.function.*;
2
3public class Main {
4 public static void main(String[] args) {
5 Predicate<Integer> isPass = m -> m >= 33; // test -> boolean
6 Function<Double, Double> withGst = p -> p * 1.18; // input -> output
7 Consumer<String> sms = msg -> System.out.println("SMS: " + msg); // use, no result
8 Supplier<String> otp = () -> "OTP " + (100000 + 47219); // no input -> value
9 BiFunction<Integer, Integer, Integer> area = (l, b) -> l * b;
10
11 System.out.println(isPass.test(45) + " " + isPass.negate().test(45));
12 System.out.println(withGst.apply(1000.0));
13 sms.accept("Your order is out for delivery");
14 System.out.println(otp.get());
15 System.out.println(area.apply(12, 10));
16 Function<Double, Double> discount = p -> p * 0.9;
17 System.out.println(discount.andThen(withGst).apply(1000.0)); // chain
18 }
19}
Terminal
D:\java-practice> java Main.java
true false
1180.0
SMS: Your order is out for delivery
OTP 147219
120
1062.0
💡 Concept in shortjava.util.function has ready functional interfaces, so you rarely write your own. Each has one method: test, apply, accept, get. They can be combined: negate(), andThen().
InterfaceShape
Predicate<T>T -> boolean
Function<T,R>T -> R
Consumer<T>T -> nothing
Supplier<T>nothing -> T
Module 17Method refs

Method References: Even Shorter Lambdas

Main.java  JAVA
1import java.util.*;
2
3public class Main {
4 static boolean isLong(String s) { return s.length() > 6; }
5
6 public static void main(String[] args) {
7 List<String> cities = new ArrayList<>(List.of("ranchi", "dumka", "jamshedpur", "giridih", "deoghar"));
8 cities.replaceAll(String::toUpperCase); // same as s -> s.toUpperCase()
9 cities.forEach(System.out::println); // same as s -> System.out.println(s)
10 cities.removeIf(Main::isLong); // static method of our class
11 cities.sort(Comparator.comparing(String::length));
12 System.out.println(cities);
13 }
14}
Terminal
D:\java-practice> java Main.java
RANCHI
DUMKA
JAMSHEDPUR
GIRIDIH
DEOGHAR
[DUMKA, RANCHI]
💡 Concept in shortWhen a lambda only calls one existing method, write Class::method instead. Four forms: String::toUpperCase (on the item), Main::isLong (static), System.out::println (on an object), ArrayList::new (constructor).
Module 17Streams

Streams: A Pipeline for Data

sourceorders.stream()filtercity == Ranchimapto amountsortedhigh firstcollecttoList()data flows through each stage; grey items are dropped by filterintermediate operations are lazy; nothing runs until the terminal operation (collect)
📄 Loop vs stream (file on disk)TXT
1// loop: 6 lines
2List<Integer> big = new ArrayList<>();
3for (Order o : orders)
4 if (o.city().equals("Ranchi")) big.add(o.amount());
5Collections.sort(big, Collections.reverseOrder());
6
7// stream: 1 statement
8List<Integer> big = orders.stream()
9 .filter(o -> o.city().equals("Ranchi"))
10 .map(Order::amount)
11 .sorted(Comparator.reverseOrder())
12 .toList();
💡 Concept in shortA stream processes a collection step by step: source -> zero or more intermediate operations (filter, map, sorted) -> one terminal operation (collect, sum, count, forEach). The original list is not changed.
IntermediateTerminal
filter, map, sortedtoList, collect
distinct, limit, skipcount, sum, average
returns a Streamreturns a result
Module 17First stream

filter, map, sorted, limit, toList

Main.java  JAVA
1import java.util.*;
2
3record Product(String name, String category, int price, double rating) { }
4
5public class Main {
6 public static void main(String[] args) {
7 List<Product> all = List.of(
8 new Product("Kurta", "Fashion", 899, 4.1), new Product("Earbuds", "Electronics", 1499, 4.3),
9 new Product("Saree", "Fashion", 2499, 4.6), new Product("Power bank", "Electronics", 999, 4.4),
10 new Product("Jacket", "Fashion", 1999, 3.9), new Product("Smart watch", "Electronics", 2999, 4.0));
11
12 List<String> goodFashion = all.stream()
13 .filter(p -> p.category().equals("Fashion"))
14 .filter(p -> p.rating() >= 4.0)
15 .sorted(Comparator.comparingInt(Product::price))
16 .map(p -> p.name() + " Rs " + p.price())
17 .toList();
18 System.out.println(goodFashion);
19
20 List<String> top2 = all.stream()
21 .sorted(Comparator.comparingDouble(Product::rating).reversed())
22 .limit(2)
23 .map(Product::name)
24 .toList();
25 System.out.println("Top rated: " + top2);
26 }
27}
Terminal
D:\java-practice> java Main.java
[Kurta Rs 899, Saree Rs 2499]
Top rated: [Saree, Power bank]
💡 Concept in shortfilter keeps items that pass a test, map changes each item into something else, sorted orders them, limit(n) keeps the first n, toList() collects the result.
RememberRead a pipeline top to bottom like a sentence: "from all products, keep Fashion, keep rating 4+, sort by price, turn into text".
Module 17Animation

Watch Items Flow Through a Stream

marks.stream()

0
78
1
28
2
91
3
45
4
12
5
66
List<Integer> marks = List.of(78, 28, 91, 45, 12, 66);
Starting value.
💡 Concept in shortEach step produces a new stream from the previous one. The source list marks stays unchanged; the final .toList() would give [96, 83, 71].
jshell (Java interactive shell)
// jshell: type Java and see the answer at once. Press Next line.
0 / 4
Module 17Reduce

Numbers from Streams: count, sum, average, max

Main.java  JAVA
1import java.util.*;
2import java.util.stream.*;
3
4record Order(String city, int amount) { }
5
6public class Main {
7 public static void main(String[] args) {
8 List<Order> orders = List.of(new Order("Ranchi", 450), new Order("Dhanbad", 900), new Order("Ranchi", 1200),
9 new Order("Bokaro", 300), new Order("Ranchi", 300));
10 long ranchiCount = orders.stream().filter(o -> o.city().equals("Ranchi")).count();
11 int total = orders.stream().mapToInt(Order::amount).sum();
12 double avg = orders.stream().mapToInt(Order::amount).average().orElse(0);
13 Optional<Order> biggest = orders.stream().max(Comparator.comparingInt(Order::amount));
14 boolean anyBig = orders.stream().anyMatch(o -> o.amount() > 1000);
15 IntSummaryStatistics st = orders.stream().mapToInt(Order::amount).summaryStatistics();
16
17 System.out.println("Ranchi orders: " + ranchiCount + ", total Rs " + total + ", avg Rs " + avg);
18 System.out.println("Biggest: " + biggest.get() + ", any above 1000? " + anyBig);
19 System.out.println(st);
20 System.out.println(IntStream.rangeClosed(1, 5).map(x -> x * x).boxed().toList());
21 }
22}
Terminal
D:\java-practice> java Main.java
Ranchi orders: 3, total Rs 3150, avg Rs 630.0
Biggest: Order[city=Ranchi, amount=1200], any above 1000? true
IntSummaryStatistics{count=5, sum=3150, min=300, average=630.000000, max=1200}
[1, 4, 9, 16, 25]
💡 Concept in shortmapToInt turns objects into numbers so you can call sum(), average(), max(). Optional wraps a result that may be missing: use orElse. anyMatch/allMatch answer yes/no questions.
Module 17Collectors

Collectors: groupingBy, counting, joining, toMap

Main.java  JAVA
1import java.util.*;
2import java.util.stream.*;
3
4record Student(String name, String city, int marks) { }
5
6public class Main {
7 public static void main(String[] args) {
8 List<Student> s = List.of(new Student("Aman", "Ranchi", 78), new Student("Pooja", "Ramgarh", 91), new Student("Imran", "Ranchi", 64),
9 new Student("Kavya", "Khunti", 88), new Student("Bittu", "Ramgarh", 55), new Student("Asha", "Ranchi", 95));
10
11 Map<String, Long> perCity = s.stream().collect(Collectors.groupingBy(Student::city, TreeMap::new, Collectors.counting()));
12 Map<String, Double> avgCity = s.stream().collect(Collectors.groupingBy(Student::city, TreeMap::new, Collectors.averagingInt(Student::marks)));
13 Map<Boolean, List<String>> pass = s.stream().collect(Collectors.partitioningBy(x -> x.marks() >= 75,
14 Collectors.mapping(Student::name, Collectors.toList())));
15 String names = s.stream().map(Student::name).sorted().collect(Collectors.joining(", ", "[", "]"));
16
17 System.out.println("Count: " + perCity);
18 System.out.println("Average: " + avgCity);
19 System.out.println("75+: " + pass.get(true) + " below: " + pass.get(false));
20 System.out.println("All: " + names);
21 }
22}
Terminal
D:\java-practice> java Main.java
Count: {Khunti=1, Ramgarh=2, Ranchi=3}
Average: {Khunti=88.0, Ramgarh=73.0, Ranchi=79.0}
75+: [Aman, Pooja, Kavya, Asha] below: [Imran, Bittu]
All: [Aman, Asha, Bittu, Imran, Kavya, Pooja]
💡 Concept in shortcollect(Collectors.xxx) builds complex results. groupingBy = "per category" reports, partitioningBy = split in two, joining = one String, counting/averagingInt = numbers per group.
RememberThis replaces the whole "Map + computeIfAbsent + loop" pattern from Module 16.
Module 17Hands-on

Code Lab: Try It Yourself

Main.java
Output of the starter code
D:\java-practice> java Main.java
Spent: Rs 14699
{Food=4200, Recharge=299, Rent=9000, Travel=1200}
Change the code, then run it on your computer: ⬇ Download → open a terminal in that folder → java Main.java. No JDK yet? Open an online Java compiler and paste the code (Copy).
Your tasks
  1. Print savings = credits - debits
  2. Find the category with the highest spending
  3. List debits above Rs 1000 sorted by amount
  4. Print each category as a % of total spending
PracticePractice 1 of 10 · Easy

Lambda Calculator

EasyScenario. A calculator stores operations as lambdas in a map.
💡 Concept used: BinaryOperator lambdas as values in a Map.

Your tasks

  1. Map<String, BinaryOperator<Double>>
  2. +, -, *, / as lambdas
  3. Apply each to 12 and 4
🏢 Used in real projects: Command dispatchers and rule engines store behaviour in maps.
LambdaCalc.java  JAVA
1import java.util.*;
2import java.util.function.*;
3
4public class LambdaCalc {
5 public static void main(String[] args) {
6 Map<String, BinaryOperator<Double>> ops = new LinkedHashMap<>();
7 ops.put("+", (a, b) -> a + b);
8 ops.put("-", (a, b) -> a - b);
9 ops.put("*", (a, b) -> a * b);
10 ops.put("/", (a, b) -> a / b);
11 ops.put("^", Math::pow);
12 ops.forEach((sym, f) -> System.out.println("12 " + sym + " 4 = " + f.apply(12.0, 4.0)));
13 }
14}
PracticePractice 2 of 10 · Easy

Filter Even and Square

EasyScenario. A maths quiz app prepares numbers.
💡 Concept used: A basic stream: filter, map, toList.

Your tasks

  1. Numbers 1-15
  2. Keep even ones
  3. Square them
  4. Print the list and sum
🏢 Used in real projects: Data preparation steps in analytics are streams of filter and map.
EvenSquares.java  JAVA
1import java.util.*;
2import java.util.stream.*;
3
4public class EvenSquares {
5 public static void main(String[] args) {
6 List<Integer> sq = IntStream.rangeClosed(1, 15).filter(n -> n % 2 == 0).map(n -> n * n).boxed().toList();
7 System.out.println(sq);
8 System.out.println("Sum: " + sq.stream().mapToInt(Integer::intValue).sum());
9 }
10}
PracticePractice 3 of 10 · Easy

Name Formatter with Streams

EasyScenario. A certificate printer cleans a list of names.
💡 Concept used: map with method references, distinct, sorted, joining.

Your tasks

  1. Trim and title-case names
  2. Remove duplicates
  3. Sort and join with commas
🏢 Used in real projects: Data cleaning before printing or saving.
Names.java  JAVA
1import java.util.*;
2import java.util.stream.*;
3
4public class Names {
5 public static void main(String[] args) {
6 List<String> raw = List.of(" aditi ", "RAHUL", "aditi", "sneha ", "Rahul");
7 String out = raw.stream()
8 .map(String::trim)
9 .map(s -> s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase())
10 .distinct()
11 .sorted()
12 .collect(Collectors.joining(", "));
13 System.out.println(out);
14 }
15}
PracticePractice 4 of 10 · Easy

Product Search Filter

EasyScenario. A shopping app filters by category, max price and min rating, then sorts.
💡 Concept used: Building a pipeline from user choices; Predicate.and to combine conditions.

Your tasks

  1. Predicates for category, price, rating
  2. Combine with and()
  3. Sort by price and print
🏢 Used in real projects: The filter panel on Amazon/Flipkart builds predicates like these.
Search.java  JAVA
1import java.util.*;
2import java.util.function.*;
3
4record Product(String name, String cat, int price, double rating) { }
5
6public class Search {
7 public static void main(String[] args) {
8 List<Product> all = List.of(new Product("Earbuds", "Audio", 1499, 4.3), new Product("Speaker", "Audio", 2499, 4.5), new Product("Headphones", "Audio", 999, 3.8),
9 new Product("Soundbar", "Audio", 6999, 4.4), new Product("Mouse", "PC", 499, 4.2));
10 Predicate<Product> audio = p -> p.cat().equals("Audio");
11 Predicate<Product> budget = p -> p.price() <= 3000;
12 Predicate<Product> good = p -> p.rating() >= 4.0;
13 all.stream().filter(audio.and(budget).and(good))
14 .sorted(Comparator.comparingInt(Product::price))
15 .forEach(p -> System.out.println(p.name() + " Rs " + p.price() + " *" + p.rating()));
16 }
17}
PracticePractice 5 of 10 · Easy

Class Result Summary

EasyScenario. Get pass count, average, topper and grade-wise lists from a mark list.
💡 Concept used: count, average, max with Comparator, and groupingBy for grades.

Your tasks

  1. record Student(name, marks)
  2. count passed, average
  3. topper with max
  4. group names by grade
🏢 Used in real projects: School ERP dashboards compute these numbers with streams or SQL.
Summary.java  JAVA
1import java.util.*;
2import java.util.stream.*;
3
4record Student(String name, int marks) {
5 String grade() { return marks >= 90 ? "A+" : marks >= 75 ? "A" : marks >= 33 ? "B" : "F"; }
6}
7
8public class Summary {
9 public static void main(String[] args) {
10 List<Student> c = List.of(new Student("Aman", 78), new Student("Bina", 95), new Student("Chirag", 28), new Student("Diya", 88), new Student("Eshan", 61));
11 System.out.println("Passed: " + c.stream().filter(s -> s.marks() >= 33).count());
12 System.out.printf("Average: %.1f%n", c.stream().mapToInt(Student::marks).average().orElse(0));
13 System.out.println("Topper: " + c.stream().max(Comparator.comparingInt(Student::marks)).get().name());
14 Map<String, List<String>> byGrade = c.stream().collect(Collectors.groupingBy(Student::grade, TreeMap::new, Collectors.mapping(Student::name, Collectors.toList())));
15 System.out.println(byGrade);
16 }
17}
PracticePractice 6 of 10 · Medium

Order Analytics

MediumScenario. A food delivery startup analyses orders: revenue per city, top dish, and average order value.
💡 Concept used: groupingBy with summingInt, counting and finding the max entry.

Your tasks

  1. record Order(city, dish, amount)
  2. Revenue per city
  3. Most ordered dish
  4. Average order value
🏢 Used in real projects: Startup dashboards (Swiggy/Zomato style) are built on these aggregations.
Analytics.java  JAVA
1import java.util.*;
2import java.util.stream.*;
3
4record Order(String city, String dish, int amount) { }
5
6public class Analytics {
7 public static void main(String[] args) {
8 List<Order> o = List.of(new Order("Ranchi", "Litti Chokha", 180), new Order("Ranchi", "Biryani", 320), new Order("Dhanbad", "Litti Chokha", 160),
9 new Order("Ranchi", "Litti Chokha", 200), new Order("Bokaro", "Momos", 120), new Order("Dhanbad", "Biryani", 300));
10 System.out.println("Revenue: " + o.stream().collect(Collectors.groupingBy(Order::city, TreeMap::new, Collectors.summingInt(Order::amount))));
11 Map<String, Long> dishCount = o.stream().collect(Collectors.groupingBy(Order::dish, Collectors.counting()));
12 String top = dishCount.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey();
13 System.out.println("Top dish: " + top + " (" + dishCount.get(top) + " orders)");
14 System.out.printf("Average order: Rs %.2f%n", o.stream().mapToInt(Order::amount).average().orElse(0));
15 }
16}
PracticePractice 7 of 10 · Medium

Word Frequency Top 5

MediumScenario. Find the 5 most used words in a paragraph, ignoring case and punctuation.
💡 Concept used: flatMap-free pipeline: split, map, filter, groupingBy counting, sort entries by value.

Your tasks

  1. Clean text with replaceAll and toLowerCase
  2. Count words with groupingBy
  3. Sort entries by count desc then word
  4. Print top 5
🏢 Used in real projects: Trending hashtags and keyword tools count words like this.
TopWords.java  JAVA
1import java.util.*;
2import java.util.stream.*;
3
4public class TopWords {
5 public static void main(String[] args) {
6 String text = "Ranchi is green. Ranchi has waterfalls, and the waterfalls of Ranchi are famous. The city is calm and the people are kind.";
7 Map<String, Long> freq = Arrays.stream(text.toLowerCase().replaceAll("[^a-z ]", "").split("\\s+"))
8 .filter(w -> w.length() > 2)
9 .collect(Collectors.groupingBy(w -> w, Collectors.counting()));
10 freq.entrySet().stream()
11 .sorted(Map.Entry.<String, Long>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))
12 .limit(5)
13 .forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
14 }
15}
PracticePractice 8 of 10 · Medium

Employee Report with Collectors

MediumScenario. HR wants per-department headcount, average salary, highest earner and a comma list of names.
💡 Concept used: groupingBy with different downstream collectors, maxBy, and summarizing statistics.

Your tasks

  1. record Emp(name, dept, salary)
  2. Headcount and average per dept
  3. Highest earner per dept (maxBy)
  4. Company salary statistics
🏢 Used in real projects: HR analytics and payroll summaries.
HrReport.java  JAVA
1import java.util.*;
2import java.util.stream.*;
3
4record Emp(String name, String dept, int salary) { }
5
6public class HrReport {
7 public static void main(String[] args) {
8 List<Emp> e = List.of(new Emp("Asha", "IT", 72000), new Emp("Binod", "Sales", 41000), new Emp("Chhaya", "IT", 88000),
9 new Emp("Dinesh", "HR", 39000), new Emp("Esha", "Sales", 52000), new Emp("Farhan", "IT", 65000));
10 Map<String, List<Emp>> byDept = e.stream().collect(Collectors.groupingBy(Emp::dept, TreeMap::new, Collectors.toList()));
11 byDept.forEach((d, list) -> {
12 double avg = list.stream().mapToInt(Emp::salary).average().orElse(0);
13 Emp top = list.stream().max(Comparator.comparingInt(Emp::salary)).get();
14 String names = list.stream().map(Emp::name).collect(Collectors.joining(","));
15 System.out.printf("%-5s %d staff, avg %,.0f, top %s [%s]%n", d, list.size(), avg, top.name(), names);
16 });
17 System.out.println(e.stream().mapToInt(Emp::salary).summaryStatistics());
18 }
19}
PracticePractice 9 of 10 · Hard

Railway Booking Analytics

HardScenario. Analyse a day's bookings from Hatia: revenue per class, busiest train, waitlisted passengers, and fare bands.
💡 Concept used: A complete analytics task with streams: filtering, grouping, partitioning, sorting and formatted output.

Your tasks

  1. record Booking(train, cls, fare, status)
  2. Revenue per class (only CONFIRMED)
  3. Busiest train by count
  4. Partition confirmed vs waitlist; fare bands with groupingBy
🏢 Used in real projects: Booking platforms run such analytics for pricing and capacity planning.
RailAnalytics.java  JAVA
1import java.util.*;
2import java.util.stream.*;
3
4record Booking(String train, String cls, int fare, String status) { }
5
6public class RailAnalytics {
7 public static void main(String[] args) {
8 List<Booking> b = List.of(new Booking("Rajdhani", "3A", 2850, "CNF"), new Booking("Rajdhani", "2A", 4100, "CNF"), new Booking("Garib Rath", "3A", 1350, "WL"),
9 new Booking("Hatia-Patna", "SL", 380, "CNF"), new Booking("Hatia-Patna", "SL", 380, "WL"), new Booking("Rajdhani", "3A", 2850, "CNF"),
10 new Booking("Hatia-Patna", "3A", 1020, "CNF"), new Booking("Garib Rath", "3A", 1350, "CNF"));
11 System.out.println("Revenue (CNF): " + b.stream().filter(x -> x.status().equals("CNF"))
12 .collect(Collectors.groupingBy(Booking::cls, TreeMap::new, Collectors.summingInt(Booking::fare))));
13 Map.Entry<String, Long> busy = b.stream().collect(Collectors.groupingBy(Booking::train, Collectors.counting()))
14 .entrySet().stream().max(Map.Entry.comparingByValue()).get();
15 System.out.println("Busiest: " + busy.getKey() + " (" + busy.getValue() + ")");
16 Map<Boolean, Long> cnf = b.stream().collect(Collectors.partitioningBy(x -> x.status().equals("CNF"), Collectors.counting()));
17 System.out.println("Confirmed " + cnf.get(true) + ", waitlisted " + cnf.get(false));
18 System.out.println("Fare bands: " + b.stream().collect(Collectors.groupingBy(x -> x.fare() < 1000 ? "budget" : x.fare() < 3000 ? "mid" : "premium", TreeMap::new, Collectors.counting())));
19 }
20}
PracticePractice 10 of 10 · Hard

Lazy Evaluation and Infinite Streams

HardScenario. Generate the first 10 numbers that are both prime and end in 7, and watch how little work a lazy stream does.
💡 Concept used: Streams are lazy: iterate can be infinite; peek shows which elements are actually processed; limit stops early.

Your tasks

  1. Stream.iterate(2, n -> n + 1) as an infinite source
  2. filter isPrime and ends with 7
  3. limit(10)
  4. count how many numbers were checked with peek
🏢 Used in real projects: Lazy streams process huge or endless data (log lines, sensor feeds) without loading everything.
LazyPrimes.java  JAVA
1import java.util.*;
2import java.util.stream.*;
3
4public class LazyPrimes {
5 static boolean isPrime(int n) {
6 if (n < 2) return false;
7 for (int d = 2; d * d <= n; d++) if (n % d == 0) return false;
8 return true;
9 }
10 public static void main(String[] args) {
11 int[] checked = {0};
12 List<Integer> r = Stream.iterate(2, n -> n + 1)
13 .peek(n -> checked[0]++)
14 .filter(n -> n % 10 == 7)
15 .filter(LazyPrimes::isPrime)
16 .limit(10)
17 .toList();
18 System.out.println(r);
19 System.out.println("Numbers examined: " + checked[0] + " (the stream stopped as soon as it had 10)");
20 }
21}
Module 17Recap

Module 17 Recap & Quiz

What you learned

  • 1Lambda (params) -> body implements a functional interface
  • 2Predicate, Function, Consumer, Supplier, BiFunction, BinaryOperator
  • 3Method references: String::length, System.out::println
  • 4Stream = source -> intermediate (filter, map, sorted, limit) -> terminal
  • 5Numbers: mapToInt, sum, average, count, max, Optional
  • 6Collectors: toList, joining, groupingBy, partitioningBy, counting

Quick quiz

list.stream().filter(...) changes the original list?

Streams never modify the source.

Which is a terminal operation?

count produces a result and ends the stream.

s -> s.toUpperCase() as a method reference is...

Class::method on each item.
PART 4 COMPLETE

Well done!

You finished Collections, Generics & Streams: 4 modules and 40 practice examples.

Before moving on

  • Re-type every practice example yourself without looking
  • Save your work in D:\java-practice\part4
  • Try the quizzes again until you get all of them right
  • Change one thing in each example and predict the output before you run it
  • Solve the Hard examples without looking at the solution first
{ } Java java Main.java main()
☕ Code Lab🌐 Online compiler
Edit the code here. Java runs on your computer (or an online compiler), not in the browser.
Expected output of the original code
Run it on your computer
  1. Install JDK 21 (adoptium.net) and check: java -version
  2. Download .java into D:\java-practice
  3. Open a terminal there and type java Main.java
  4. Or click Copy code and paste it into the online compiler