KNOWLEDGEWALA • LEARN TEACH GROW • JAVA INTERVIEW SERIES

Java Lambda, Stream,
Virtual Threads & Critical Topics

From “What is Lambda?” to Streams, Optional, Records, Pattern Matching, CompletableFuture & Virtual Threads — one tutorial for students, juniors, experts & non-tech readers, with step-by-step LeetCode examples.

⏱ 110–140 min read📚 10 Chapters💻 30+ Runnable Programs⭐ 14 LeetCode Problems🎯 All Ages & Experience

📑 Table of Contents

  1. Chapter 1 — Why Modern Java? From Java 7 to Java 21
  2. Chapter 2 — Lambda Expressions: From Anonymous Class to 1 Line
  3. Chapter 3 — Functional Interfaces, Method References & Built-in Functions
  4. Chapter 4 — Stream API: From Loops to Pipelines (Core)
  5. Chapter 5 — Stream Deep Dive: Collectors, Grouping, Parallel Streams
  6. Chapter 6 — Optional: Stop NullPointerException Forever
  7. Chapter 7 — Records, Sealed Classes, Pattern Matching & Switch Expressions
  8. Chapter 8 — CompletableFuture & Async Programming
  9. Chapter 9 — Virtual Threads (Java 21) + Structured Concurrency
  10. Chapter 10 — Real-Time Systems, LeetCode Patterns & Interview Plan

How to use: For every topic — Story → Theory (30 sec) → Old Code (Java 7) → New Code (Modern) → Step-by-Step Dry Run → Complete Runnable Program → Real-Time Use → LeetCode → Interview Line.

How To Read • For All Ages & Experience

Read This First — Pick Your Path

🧒 Age 12–16 / School Student
Read only Story + Analogy + Easy Code. Skip “Expert Notes”. Your goal: understand idea, not memorize syntax. Try the “Try It Yourself” small tasks.
👩‍🎓 College Student / Fresher
Read Old → New → Dry Run → Complete Program. Type every program. Focus Ch 2, 4, 6. These are asked in campus interviews.
👨‍💻 Junior (0–3 yrs)
Read Problem → Easy → Optimized → LeetCode. Focus Ch 4, 5, 8, 9. Learn to convert loops to Streams in interviews.
🧑‍🏫 Expert / Senior (3+ yrs) & Non-Tech
Expert: Jump to Expert Notes + Trade-offs + Production. Non-Tech: Read only Story + Real-Time + One-Line Answer. You will understand why modern Java is faster to write and safer.
Expert Tutor Rule: Modern Java is not about “new syntax”. It is about writing less code, with fewer bugs, that is easier to read. If your Stream code is harder to read than a loop, you are using it wrong.

The 4 Words That Explain Modern Java

WordSimple MeaningExample
LambdaFunction as value — pass behaviour, not just data.list.forEach(x -> System.out.println(x))
StreamPipeline to process data — filter, transform, collect.list.stream().filter(...).map(...).toList()
OptionalBox that may be empty — forces you to handle “no value”.Optional.ofNullable(user).orElse("Guest")
Virtual ThreadLightweight thread — millions can run at once.Thread.ofVirtual().start(task)
Chapter 1 • Beginner • Why Modern Java?

Why Modern Java? From Java 7 to Java 21

Old Java was verbose. Modern Java is expressive. Same program in 30 lines becomes 5 lines — with fewer bugs.

🏪 Non-Tech Analogy: Old Java = Writing a letter by hand, posting it, waiting 5 days. Modern Java = Sending a WhatsApp message — same idea, 10x faster, instant reply. Lambda + Stream are the “WhatsApp” of Java.

1.1 Same Task — Old vs New (See the Difference)

Task: From a list of students, get names of students with marks > 80, sorted, in uppercase.

// OLD JAVA 7 — 15 lines, loops, temp lists, manual sort
List<String> result = new ArrayList<>();
for (Student s : students) {
    if (s.marks > 80) result.add(s.name.toUpperCase());
}
Collections.sort(result);

// NEW MODERN JAVA — 4 lines, pipeline, readable
List<String> result = students.stream()
    .filter(s -> s.marks > 80)
    .map(s -> s.name.toUpperCase())
    .sorted()
    .toList();

1.2 Java Version Timeline — What Interviewers Ask

VersionBig FeatureOne Line
Java 8 (2014)Lambda, Stream, Optional, Date-TimeBirth of modern Java
Java 11 (2018)var, HttpClient, String methodsLTS, production standard
Java 17 (2021)Records, Sealed Classes, Pattern MatchingLTS, modern + stable
Java 21 (2023)Virtual Threads, Structured Concurrency, Pattern MatchingLTS, current best
🗣 Interview Q: What is new in Java 8? Answer: “Lambda expressions, Stream API, Functional Interfaces, Optional, Default methods, new Date-Time API (java.time), CompletableFuture.”
🌍 Real-Time: Every modern backend (e-commerce, banking, food delivery) uses Java 17/21. If you only know Java 7 loops, you will write slow, buggy code. If you know Streams + Virtual Threads, you write fast, clean, scalable code.
Chapter 2 • Beginner to Intermediate • Lambda Core

Lambda Expressions: From Anonymous Class to 1 Line

Lambda = A function without a name, that you can pass like a value. This one idea changed Java forever.

2.1 Step-by-Step Evolution — Read in Order

Step 1 — Old Way: Anonymous Inner Class (Java 7, 7 lines)
Runnable r = new Runnable() {
    public void run() {
        System.out.println("Hello");
    }
};
new Thread(r).start();
Step 2 — Lambda: Same Work, 1 Line (Java 8+)
Runnable r = () -> System.out.println("Hello");
new Thread(r).start();

Read () -> System.out.println("Hello") as: “A function with no inputs, that prints Hello.” The -> is called arrow — it separates inputs from body.

Step 3 — Lambda With Inputs
// (a, b) are inputs, a + b is body
// Old: Comparator with 5 lines. New: 1 line.
Comparator<Integer> cmpOld = new Comparator<Integer>() {
    public int compare(Integer a, Integer b) { return a - b; }
};
Comparator<Integer> cmpNew = (a, b) -> a - b;

2.2 Lambda Syntax — All Forms (Must Know)

// No input, no return
Runnable r1 = () -> System.out.println("Hi");

// One input, one line (brackets optional for 1 input)
Consumer<String> c1 = s -> System.out.println(s);
Consumer<String> c2 = (s) -> System.out.println(s);

// Two inputs
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println(add.apply(3, 4)); // 7

// Multi-line body — need { } + return
Function<Integer, String> grade = (marks) -> {
    if (marks >= 90) return "A";
    else if (marks >= 75) return "B";
    else return "C";
};
System.out.println(grade.apply(92)); // A

2.3 Complete Program — Lambda in Real Life (Sorting, Filtering, Thread)

import java.util.*;
public class LambdaComplete {
    record Student(String name, int marks) {}
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>(List.of(
            new Student("Asha", 90), new Student("Ravi", 70), new Student("Meena", 95)));

        // 1) Lambda in Thread
        new Thread(() -> System.out.println("Thread running: " + Thread.currentThread().getName())).start();

        // 2) Lambda in Sorting — sort by marks descending
        students.sort((a, b) -> b.marks - a.marks);
        System.out.println("Sorted by marks desc: " + students);

        // 3) Lambda in forEach
        students.forEach(s -> System.out.println("Student: " + s.name + " = " + s.marks));

        // 4) Lambda with custom logic — pass behaviour as argument
        printIf(students, s -> s.marks > 80); // only toppers
    }
    // Higher-order function: takes a function as input
    static void printIf(List<Student> list, java.util.function.Predicate<Student> check) {
        for (Student s : list) if (check.test(s)) System.out.println("Pass: " + s);
    }
}
Common Mistake — Effectively Final: Lambda can use variables from outside, but they must be effectively final (not changed after). This fails:
int count = 0;
list.forEach(x -> count++); // COMPILE ERROR — count must be final / effectively final
// Fix: Use AtomicInteger or int[1] or Stream count()
🍳 Non-Tech Analogy: Lambda = Recipe card. You don’t cook now, you give the recipe to someone else (“when you get ingredients, follow this”). forEach is the cook — it calls your recipe for each item.
🗣 Interview Q: What is Lambda? Answer: “A concise way to represent an anonymous function — an implementation of a Functional Interface (single abstract method). It lets us pass behaviour as an argument, e.g., sorting logic, filtering logic, thread task.”

⭐ LeetCode 1636 — Sort Array by Increasing Frequency EASY • Lambda + Sorting

Problem: Sort by frequency (low to high), if tie, by value (high to low). [1,1,2,2,2,3] → [3,1,1,2,2,2].

import java.util.*;
public class SortByFrequency {
    public int[] frequencySort(int[] nums) {
        Map<Integer, Integer> freq = new HashMap<>();
        for (int n : nums) freq.merge(n, 1, Integer::sum);
        // Lambda Comparator: first by freq (asc), then by value (desc)
        Integer[] boxed = Arrays.stream(nums).boxed().toArray(Integer[]::new);
        Arrays.sort(boxed, (a, b) -> {
            int cmp = freq.get(a) - freq.get(b);
            return cmp != 0 ? cmp : b - a;
        });
        return Arrays.stream(boxed).mapToInt(Integer::intValue).toArray();
    }
    public static void main(String[] args) {
        System.out.println(Arrays.toString(new SortByFrequency().frequencySort(new int[]{1,1,2,2,2,3})));
    }
}
Chapter 3 • Intermediate • Functional Interfaces

Functional Interfaces, Method References & Built-in Functions

Lambda only works with Functional Interfaces — interfaces with exactly ONE abstract method. Learn the 4 built-in ones, and you can use Lambda everywhere.

3.1 What is Functional Interface?

// Custom Functional Interface — @FunctionalInterface is optional but good practice
@FunctionalInterface
interface Calculator {
    int calculate(int a, int b); // exactly ONE abstract method
    // Default + static methods are allowed — they do not count
    default void print() { System.out.println("Calculator"); }
    static void info() { System.out.println("Math"); }
}
// Usage with Lambda:
public class FunctionalInterfaceComplete {
    public static void main(String[] args) {
        Calculator add = (a, b) -> a + b;
        Calculator multiply = (a, b) -> a * b;
        System.out.println("Add: " + add.calculate(3, 4)); // 7
        System.out.println("Multiply: " + multiply.calculate(3, 4)); // 12
    }
}

3.2 The 4 Built-in Functional Interfaces — Memorize This Table

InterfaceMethodInput → OutputExample
Predicate<T>test(T)T → booleanx -> x > 18 (is adult?)
Function<T,R>apply(T)T → Rs -> s.length() (String → Integer)
Consumer<T>accept(T)T → voids -> System.out.println(s)
Supplier<T>get()void → T() -> new Random().nextInt()
BiFunction<T,U,R>apply(T,U)(T,U) → R(a,b) -> a + b
BiPredicate, BiConsumerSame with 2 inputs(T,U) → boolean / void(a,b) -> a.equals(b)

3.3 Complete Program — All 4 in One Place

import java.util.function.*;
import java.util.*;
public class BuiltInFunctionsComplete {
    public static void main(String[] args) {
        // Predicate: test condition
        Predicate<Integer> isEven = x -> x % 2 == 0;
        System.out.println("Is 4 even? " + isEven.test(4)); // true
        // Chaining: and / or / negate
        Predicate<Integer> isAdultAndEven = ((Predicate<Integer>)(x -> x >= 18)).and(isEven);
        System.out.println("Is 20 adult+even? " + isAdultAndEven.test(20)); // true

        // Function: transform + chaining with andThen / compose
        Function<String, Integer> length = s -> s.length();
        Function<Integer, String> toMsg = n -> "Length = " + n;
        System.out.println(length.andThen(toMsg).apply("Hello")); // Length = 5

        // Consumer: consume, no return + chaining
        Consumer<String> print = s -> System.out.println("Hello " + s);
        Consumer<String> shout = s -> System.out.println(s.toUpperCase() + "!!!");
        print.andThen(shout).accept("Asha"); // Hello Asha + ASHA!!!

        // Supplier: supply value lazily (only when called)
        Supplier<String> lazy = () -> { System.out.println("Supplier called"); return "Data from DB"; };
        System.out.println("Before get() — supplier NOT called yet");
        System.out.println(lazy.get()); // Now called
    }
}

3.4 Method References — Lambda Short Form

When Lambda just calls an existing method, use :: — shorter and clearer.

import java.util.*;
public class MethodReferenceComplete {
    public static void main(String[] args) {
        List<String> names = List.of("Asha", "Ravi", "Meena");
        // Lambda: s -> System.out.println(s)
        // Method Ref: System.out::println (same, shorter)
        names.forEach(System.out::println);

        // 4 Types of Method References:
        // 1) Static: ClassName::staticMethod
        List<String> nums = List.of("1", "2", "3");
        nums.stream().map(Integer::parseInt).forEach(System.out::println); // 1,2,3

        // 2) Instance of object: obj::method
        String prefix = "Hello ";
        names.stream().map(prefix::concat).forEach(System.out::println); // Hello Asha...

        // 3) Instance of type: ClassName::instanceMethod
        names.stream().map(String::toUpperCase).forEach(System.out::println); // ASHA...

        // 4) Constructor: ClassName::new
        List<String> words = List.of("A", "B");
        List<StringBuilder> builders = words.stream().map(StringBuilder::new).toList();
        System.out.println("Builders: " + builders);
    }
}
🧑‍🏫 Expert Note — Lambda vs Method Reference: Use method reference when Lambda is just a direct call (s -> System.out.println(s) → System.out::println). Use Lambda when you need logic (s -> s.length() > 3). Interviewers check readability, not just correctness.
🗣 Interview Q: What is Functional Interface? Can it have default methods? Answer: “Interface with exactly one abstract method. Yes, it can have any number of default + static methods — they don’t count. Example: Runnable, Comparator, Predicate.”
Chapter 4 • Intermediate • Stream Core

Stream API: From Loops to Pipelines (Core)

Stream is not a collection. It is a pipeline to process data. Think: Water pipeline — water (data) flows in, filters clean it, transformers change it, bucket (collect) stores result.

🏭 Non-Tech Analogy: Factory line: Raw mangoes → Wash (filter bad) → Peel (map) → Pack (collect). You don’t store mangoes in the line, you process them as they flow. Stream is the factory line. Collection is the warehouse.

4.1 Stream Pipeline — 3 Parts

list.stream()          // 1) SOURCE: where data comes from (List, array, file)
    .filter(...)       // 2) INTERMEDIATE: filter, map, sorted — lazy, no work yet
    .map(...)
    .collect(...)      // 3) TERMINAL: forEach, collect, count — triggers work
// Intermediate = lazy (no execution until terminal). Terminal = eager (executes).

4.2 Step-by-Step Dry Run — Read Slowly

Task: From [1,2,3,4,5,6], get squares of even numbers: [4,16,36].
List<Integer> nums = List.of(1,2,3,4,5,6);
List<Integer> result = nums.stream()
    .filter(n -> n % 2 == 0) // keep 2,4,6
    .map(n -> n * n)         // 4,16,36
    .toList();
System.out.println(result); // [4,16,36]

Dry Run: Stream takes 1 → filter? 1 is odd → drop. Takes 2 → even → map to 4 → collect. Takes 3 → drop. Takes 4 → 16. Takes 5 → drop. Takes 6 → 36. Done. Key: Stream processes one element at a time through full pipeline (not filter-all then map-all). This is called loop fusion — efficient.

4.3 Complete Program — All Intermediate Operations

import java.util.*;
import java.util.stream.*;
public class StreamIntermediateComplete {
    public static void main(String[] args) {
        List<String> names = List.of("Asha", "Ravi", "Meena", "Asha", "Arjun", "Ravi");
        System.out.println("Original: " + names);

        // filter: keep only names starting with A
        System.out.println("Filter A: " + names.stream().filter(s -> s.startsWith("A")).toList());

        // map: transform each element
        System.out.println("Map upper: " + names.stream().map(String::toUpperCase).toList());

        // distinct: remove duplicates
        System.out.println("Distinct: " + names.stream().distinct().toList());

        // sorted: natural order
        System.out.println("Sorted: " + names.stream().sorted().toList());
        // sorted custom: by length, then alphabetically
        System.out.println("Sorted by length: " + names.stream().distinct().sorted(Comparator.comparingInt(String::length).thenComparing(s -> s)).toList());

        // limit / skip: pagination
        System.out.println("Limit 3: " + names.stream().limit(3).toList());
        System.out.println("Skip 2: " + names.stream().skip(2).toList());
        System.out.println("Page 2 (skip 2, limit 2): " + names.stream().skip(2).limit(2).toList());

        // peek: debug — see elements flowing (does NOT change stream)
        System.out.println("Peek debug:");
        names.stream().filter(s -> s.length() > 3).peek(s -> System.out.println("  Passing filter: " + s)).toList();

        // flatMap: flatten List of Lists → single List
        List<List<Integer>> nested = List.of(List.of(1,2), List.of(3,4), List.of(5));
        System.out.println("FlatMap: " + nested.stream().flatMap(List::stream).toList()); // [1,2,3,4,5]
        // flatMap for words → characters: "Hi" → ['H','i']
        List<String> words = List.of("Hi", "Bye");
        System.out.println("Chars: " + words.stream().flatMap(s -> s.chars().mapToObj(c -> (char)c)).toList());
    }
}

4.4 Complete Program — All Terminal Operations

import java.util.*;
import java.util.stream.*;
public class StreamTerminalComplete {
    public static void main(String[] args) {
        List<Integer> nums = List.of(1,2,3,4,5);
        // forEach: action for each
        nums.stream().forEach(n -> System.out.print(n + " ")); System.out.println();
        // count: how many?
        System.out.println("Count >3: " + nums.stream().filter(n -> n > 3).count()); // 2
        // anyMatch / allMatch / noneMatch: true/false checks (short-circuit)
        System.out.println("Any even? " + nums.stream().anyMatch(n -> n % 2 == 0)); // true
        System.out.println("All positive? " + nums.stream().allMatch(n -> n > 0)); // true
        System.out.println("None negative? " + nums.stream().noneMatch(n -> n < 0)); // true
        // findFirst / findAny: Optional result
        System.out.println("First even: " + nums.stream().filter(n -> n % 2 == 0).findFirst()); // Optional[2]
        // min / max
        System.out.println("Max: " + nums.stream().max(Integer::compareTo)); // Optional[5]
        // reduce: combine all into one (sum)
        System.out.println("Sum via reduce: " + nums.stream().reduce(0, (a,b) -> a + b)); // 15
        System.out.println("Sum via mapToInt: " + nums.stream().mapToInt(Integer::intValue).sum()); // 15 (faster)
        // collect: to List / Set / Map
        System.out.println("To Set: " + nums.stream().collect(Collectors.toSet()));
        // toArray
        System.out.println("To Array: " + Arrays.toString(nums.stream().toArray()));
        // Stream is single-use!
        Stream<Integer> s = nums.stream();
        s.forEach(n -> {});
        // s.forEach(n -> {}); // IllegalStateException — stream already consumed!
        System.out.println("Rule: Stream can be used only once. Create new stream each time.");
    }
}
Common Mistakes: 1) Forgetting terminal operation — intermediate alone does NOTHING (lazy). list.stream().filter(...); does nothing, no filtering happens. 2) Reusing stream — throws IllegalStateException. 3) Using forEach to collect — use collect() instead, forEach is for side-effects (printing).

⭐ LeetCode 136 — Single Number EASY • Stream + XOR

Problem: Every number appears twice except one. Find it. [2,2,1] → 1.

import java.util.*;
public class SingleNumber {
    public int singleNumber(int[] nums) {
        // XOR: a ^ a = 0, a ^ 0 = a. All pairs cancel, single remains.
        return Arrays.stream(nums).reduce(0, (a, b) -> a ^ b);
    }
    public static void main(String[] args) {
        System.out.println(new SingleNumber().singleNumber(new int[]{2,2,1})); // 1
        System.out.println(new SingleNumber().singleNumber(new int[]{4,1,2,1,2})); // 4
    }
}

Step-by-step: 0 ^ 2 = 2, 2 ^ 2 = 0, 0 ^ 1 = 1. Done in O(n) time, O(1) space.

⭐ LeetCode 217 — Contains Duplicate EASY • Stream + Distinct

import java.util.*;
public class ContainsDuplicateStream {
    public boolean containsDuplicate(int[] nums) {
        // If distinct count < total count → duplicate exists
        return Arrays.stream(nums).distinct().count() != nums.length;
    }
    public static void main(String[] args) {
        System.out.println(new ContainsDuplicateStream().containsDuplicate(new int[]{1,2,3,1})); // true
    }
}
Chapter 5 • Intermediate to Advanced • Collectors & Parallel

Stream Deep Dive: Collectors, Grouping, Parallel Streams

Collectors are the most powerful part of Streams. They can group, count, average, partition — in one line.

5.1 Complete Program — Collectors Masterclass

import java.util.*;
import java.util.stream.*;
public class CollectorsComplete {
    record Student(String name, int marks, String city) {}
    public static void main(String[] args) {
        List<Student> students = List.of(
            new Student("Asha", 90, "Mumbai"), new Student("Ravi", 70, "Delhi"),
            new Student("Meena", 95, "Mumbai"), new Student("Arjun", 60, "Delhi"),
            new Student("Priya", 85, "Mumbai"));

        // 1) toList / toSet / toMap
        System.out.println("Names: " + students.stream().map(Student::name).toList());
        Map<String, Integer> nameToMarks = students.stream()
            .collect(Collectors.toMap(Student::name, Student::marks));
        System.out.println("Name→Marks: " + nameToMarks);
        // toMap with duplicate key? Use merge function: (old, new) -> old
        // Collectors.toMap(Student::city, Student::name, (a,b) -> a + "," + b)

        // 2) groupingBy: city → list
        Map<String, List<Student>> byCity = students.stream().collect(Collectors.groupingBy(Student::city));
        System.out.println("By City: " + byCity);

        // 3) groupingBy + counting: city → count
        Map<String, Long> countByCity = students.stream().collect(Collectors.groupingBy(Student::city, Collectors.counting()));
        System.out.println("Count by City: " + countByCity); // {Mumbai=3, Delhi=2}

        // 4) groupingBy + averaging: city → avg marks
        Map<String, Double> avgByCity = students.stream().collect(
            Collectors.groupingBy(Student::city, Collectors.averagingInt(Student::marks)));
        System.out.println("Avg by City: " + avgByCity);

        // 5) partitioningBy: pass/fail (true/false)
        Map<Boolean, List<Student>> passFail = students.stream().collect(
            Collectors.partitioningBy(s -> s.marks >= 75));
        System.out.println("Pass: " + passFail.get(true).size() + " Fail: " + passFail.get(false).size());

        // 6) joining: join names with comma
        System.out.println("Joined: " + students.stream().map(Student::name).collect(Collectors.joining(", ")));
        System.out.println("Joined with [ ]: " + students.stream().map(Student::name).collect(Collectors.joining(", ", "[", "]")));

        // 7) summarizing: count + sum + min + max + avg in one pass
        IntSummaryStatistics stats = students.stream().collect(Collectors.summarizingInt(Student::marks));
        System.out.println("Stats: count=" + stats.getCount() + " avg=" + stats.getAverage() + " max=" + stats.getMax());

        // 8) maxBy / minBy: topper per city
        Map<String, Optional<Student>> topperByCity = students.stream().collect(
            Collectors.groupingBy(Student::city, Collectors.maxBy(Comparator.comparingInt(Student::marks))));
        System.out.println("Topper by City: " + topperByCity);
    }
}

5.2 Parallel Streams — When to Use, When NOT

import java.util.*;
import java.util.stream.*;
public class ParallelStreamComplete {
    public static void main(String[] args) {
        List<Integer> big = IntStream.rangeClosed(1, 10_000_000).boxed().toList();

        // Sequential: one thread
        long start = System.currentTimeMillis();
        long sumSeq = big.stream().mapToLong(Integer::longValue).sum();
        System.out.println("Sequential sum=" + sumSeq + " time=" + (System.currentTimeMillis() - start) + " ms");

        // Parallel: many threads (ForkJoinPool, cores-1 threads)
        start = System.currentTimeMillis();
        long sumPar = big.parallelStream().mapToLong(Integer::longValue).sum();
        System.out.println("Parallel sum=" + sumPar + " time=" + (System.currentTimeMillis() - start) + " ms");

        // DANGER: Parallel + shared mutable state = race condition!
        List<Integer> unsafe = new ArrayList<>();
        // big.parallelStream().forEach(unsafe::add); // WRONG: ArrayList not thread-safe, data lost!
        // FIX: Use collect (thread-safe) instead of forEach + shared list
        List<Integer> safe = big.parallelStream().filter(n -> n % 2 == 0).limit(10).toList();
        System.out.println("Safe parallel collect: " + safe);
        System.out.println("Rule: Parallel + collect = safe. Parallel + shared mutable list = BUG.");
    }
}
🧑‍🏫 Expert Note — Parallel Stream Rules: Use parallel only for: Large data (>10k), CPU-bound (calculation), stateless operations. Do NOT use for: Small data, I/O (DB/network — blocks ForkJoinPool), order-sensitive work, shared mutable state. For I/O, use custom Executor + CompletableFuture, not parallelStream.

⭐ LeetCode 49 — Group Anagrams MEDIUM • Stream + groupingBy

import java.util.*;
import java.util.stream.*;
public class GroupAnagramsStream {
    public List<List<String>> groupAnagrams(String[] strs) {
        // Key = sorted chars. Group by key in one Stream pipeline.
        return new ArrayList<>(Arrays.stream(strs)
            .collect(Collectors.groupingBy(s -> {
                char[] c = s.toCharArray(); Arrays.sort(c); return new String(c);
            })).values());
    }
    public static void main(String[] args) {
        System.out.println(new GroupAnagramsStream().groupAnagrams(new String[]{"eat","tea","tan","ate","nat","bat"}));
    }
}

⭐ LeetCode 347 — Top K Frequent MEDIUM • Stream + Collectors + Heap

import java.util.*;
import java.util.stream.*;
public class TopKFrequentStream {
    public int[] topKFrequent(int[] nums, int k) {
        // Step 1: Count frequencies with groupingBy + counting
        Map<Integer, Long> freq = Arrays.stream(nums).boxed()
            .collect(Collectors.groupingBy(n -> n, Collectors.counting()));
        System.out.println("Freq: " + freq);
        // Step 2: Sort by freq desc, take top k
        return freq.entrySet().stream()
            .sorted(Map.Entry.<Integer, Long>comparingByValue().reversed())
            .limit(k)
            .mapToInt(Map.Entry::getKey)
            .toArray();
    }
    public static void main(String[] args) {
        System.out.println(Arrays.toString(new TopKFrequentStream().topKFrequent(new int[]{1,1,1,2,2,3}, 2))); // [1,2]
    }
}
Chapter 6 • Intermediate • Null Safety

Optional: Stop NullPointerException Forever

NullPointerException is the #1 crash in Java. Optional forces you to handle “no value” — at compile time, not at runtime crash.

📦 Non-Tech Analogy: Old code = Handing someone an empty box without telling them it is empty — they open it, find nothing, crash (NPE). Optional = A box with a label: “May be empty — check before opening.” You cannot ignore the label.

6.1 Old vs New — Step-by-Step

// OLD: Null checks everywhere, easy to forget, NPE at runtime
String getCityOld(User user) {
    if (user != null) {
        Address addr = user.getAddress();
        if (addr != null) return addr.getCity();
    }
    return "Unknown";
}
// NEW: Optional chain, no nested if, no NPE
String getCityNew(User user) {
    return Optional.ofNullable(user)
        .map(User::getAddress)   // if user null → empty, skip
        .map(Address::getCity)   // if address null → empty, skip
        .orElse("Unknown");      // fallback if empty
}

6.2 Complete Program — Optional Masterclass

import java.util.*;
public class OptionalComplete {
    record Address(String city) {}
    record User(String name, Address address) {}
    public static void main(String[] args) {
        // Creating Optional
        Optional<String> present = Optional.of("Hello"); // never null — throws NPE if null
        Optional<String> maybeNull = Optional.ofNullable(null); // OK, becomes empty
        Optional<String> empty = Optional.empty();

        // Checking: isPresent / ifPresent / ifPresentOrElse
        present.ifPresent(v -> System.out.println("Present: " + v));
        maybeNull.ifPresentOrElse(
            v -> System.out.println("Value: " + v),
            () -> System.out.println("Empty — fallback needed"));

        // orElse vs orElseGet — IMPORTANT difference!
        System.out.println("orElse (eager): " + maybeNull.orElse(expensiveCall())); // expensiveCall ALWAYS runs!
        System.out.println("orElseGet (lazy): " + maybeNull.orElseGet(() -> expensiveCall())); // only if empty
        // Rule: Use orElseGet for expensive fallback (DB call). Use orElse for cheap constant.

        // orElseThrow: fail fast with clear message
        try {
            String must = maybeNull.orElseThrow(() -> new IllegalArgumentException("User not found"));
        } catch (Exception e) { System.out.println("orElseThrow: " + e.getMessage()); }

        // map vs flatMap: map = transform value, flatMap = transform to Optional (avoid Optional<Optional>)
        Optional<User> user = Optional.of(new User("Asha", new Address("Mumbai")));
        System.out.println("City via map: " + user.map(User::address).map(Address::city)); // Optional[Mumbai]
        // If getAddress returned Optional<Address>, use flatMap to avoid nested Optional

        // filter: keep only if condition
        System.out.println("Filter marks>80: " + Optional.of(90).filter(m -> m > 80)); // Optional[90]
        System.out.println("Filter marks>95: " + Optional.of(90).filter(m -> m > 95)); // Optional.empty

        // Real chaining: User → Address → City, with fallback
        User userWithNullAddr = new User("Ravi", null);
        String city = Optional.ofNullable(userWithNullAddr)
            .map(User::address).map(Address::city).orElse("Unknown");
        System.out.println("City (null address): " + city); // Unknown, no NPE!
    }
    static String expensiveCall() { System.out.println("  expensiveCall() running..."); return "Fallback"; }
}
Common Mistakes: 1) Using Optional.get() without isPresent() — throws NoSuchElementException, same as NPE. Use orElse / orElseGet / ifPresent instead. 2) Using Optional as method parameter or field — Optional is for return values only, not for fields / params. 3) Using Optional.of(null) — throws NPE immediately. Use ofNullable for possibly-null values.
🗣 Interview Q: What is Optional? When to use? Answer: “A container that may or may not hold a value. Use as return type to force caller to handle empty case. Do not use as field / parameter. Use orElseGet for lazy fallback, not orElse for expensive calls.”

⭐ LeetCode 20 — Valid Parentheses (Optional + Stack Pattern)

See Collections tutorial for full code. Optional version: Optional.ofNullable(s).filter(str -> !str.isEmpty()).orElse("") to handle null input safely — interviewers note null handling.

Chapter 7 • Intermediate to Advanced • Modern Java Features

Records, Sealed Classes, Pattern Matching & Switch Expressions

These 4 features remove boilerplate. A 50-line POJO becomes 1 line. A 20-line if-else chain becomes 5 lines.

7.1 Records — POJO in 1 Line (Java 16+)

// OLD: 50 lines — fields, constructor, getters, equals, hashCode, toString
// NEW: 1 line — all auto-generated, immutable
record UserRecord(String id, String name, int age) {}
public class RecordsComplete {
    public static void main(String[] args) {
        UserRecord u1 = new UserRecord("101", "Asha", 20);
        UserRecord u2 = new UserRecord("101", "Asha", 20);
        System.out.println("u1: " + u1); // UserRecord[id=101, name=Asha, age=20] — auto toString
        System.out.println("Equals? " + u1.equals(u2)); // true — auto equals/hashCode
        System.out.println("Name: " + u1.name()); // accessor, not getName()
        // u1.age = 21; // COMPILE ERROR — Record is immutable, no setters
        // Records are perfect for DTOs, API responses, Map keys, Stream results
        // Compact constructor for validation:
        record ValidUser(String name, int age) {
            ValidUser { if (age < 0) throw new IllegalArgumentException("Age cannot be negative"); }
        }
        System.out.println(new ValidUser("Ravi", 22));
    }
}

7.2 Sealed Classes — Control Who Can Extend You

// Only Circle, Rectangle, Triangle can extend Shape — no one else!
sealed interface Shape permits Circle, Rectangle, Triangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double w, double h) implements Shape {}
record Triangle(double base, double height) implements Shape {}
public class SealedComplete {
    // Compiler knows all subtypes — switch is exhaustive, no default needed
    static double area(Shape shape) {
        return switch (shape) {
            case Circle c -> Math.PI * c.radius() * c.radius();
            case Rectangle r -> r.w() * r.h();
            case Triangle t -> 0.5 * t.base() * t.height();
        };
    }
    public static void main(String[] args) {
        System.out.println("Circle area: " + area(new Circle(5))); // 78.5
        System.out.println("Rect area: " + area(new Rectangle(4, 5))); // 20
    }
}

7.3 Pattern Matching — instanceof Without Cast (Java 16+) + Switch (Java 21)

public class PatternMatchingComplete {
    // OLD: instanceof + manual cast (2 steps, easy to forget cast)
    static String oldDescribe(Object obj) {
        if (obj instanceof String) { String s = (String) obj; return "String len=" + s.length(); }
        else if (obj instanceof Integer) { Integer i = (Integer) obj; return "Int=" + i; }
        return "Unknown";
    }
    // NEW: Pattern matching — instanceof + cast in one step
    static String newDescribe(Object obj) {
        if (obj instanceof String s) return "String len=" + s.length(); // s auto-cast!
        else if (obj instanceof Integer i) return "Int=" + i;
        else return "Unknown";
    }
    // NEWEST: Switch with Pattern Matching (Java 21) — cleanest
    static String switchDescribe(Object obj) {
        return switch (obj) {
            case String s when s.length() > 5 -> "Long String: " + s;
            case String s -> "Short String: " + s;
            case Integer i -> "Integer: " + i;
            case null -> "Null!";
            default -> "Other: " + obj;
        };
    }
    public static void main(String[] args) {
        System.out.println(oldDescribe("Hello")); // String len=5
        System.out.println(newDescribe(123)); // Int=123
        System.out.println(switchDescribe("HelloWorld")); // Long String
        System.out.println(switchDescribe(null)); // Null! (no NPE)
        // Switch Expression: returns value, no break needed
        int day = 2;
        String dayName = switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            default -> "Other";
        };
        System.out.println("Day: " + dayName);
    }
}
🗣 Interview Q: Record vs Class? Answer: “Record is immutable, auto-generates constructor, getters, equals, hashCode, toString. Use for DTOs / data carriers. Class is mutable, has setters, can extend. Use for entities with behaviour.”
🌍 Real-Time: API response DTOs = Records. Payment types (UPI / Card / Cash) = Sealed classes. Handling different event types = Pattern Matching switch. These 3 together remove 70% of boilerplate in modern backends.
Chapter 8 • Advanced • Async

CompletableFuture & Async Programming

Old Future blocks. CompletableFuture chains. Learn to run 3 tasks in parallel and combine — this is asked in every Senior interview.

8.1 Complete Program — Sequential (Slow) vs Parallel (Fast)

import java.util.concurrent.*;
public class CompletableFutureComplete {
    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        // PARALLEL: All 3 at once = ~1 sec, not 3 sec
        CompletableFuture<String> userF = CompletableFuture.supplyAsync(() -> fetchUser());
        CompletableFuture<String> orderF = CompletableFuture.supplyAsync(() -> fetchOrders());
        CompletableFuture<String> payF = CompletableFuture.supplyAsync(() -> fetchPayments());

        // Wait for ALL, then combine
        String combined = CompletableFuture.allOf(userF, orderF, payF)
            .thenApply(v -> userF.join() + " | " + orderF.join() + " | " + payF.join())
            .get();
        System.out.println(combined);
        System.out.println("Time: " + (System.currentTimeMillis() - start) + " ms (parallel, ~1000 not 3000)");

        // Chaining: thenApply (transform) vs thenCompose (chain futures) vs thenCombine (combine 2)
        String r1 = CompletableFuture.supplyAsync(() -> 10)
            .thenApply(x -> x * 2).thenApply(x -> "Value=" + x).get();
        System.out.println(r1); // Value=20

        // Exception + fallback: if DB fails, use cache
        String r2 = CompletableFuture.<String>supplyAsync(() -> { throw new RuntimeException("DB down"); })
            .exceptionally(e -> "Fallback: Cached Data").get();
        System.out.println("Fallback: " + r2);

        // Timeout: orTimeout / completeOnTimeout
        String r3 = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(5000); } catch (Exception e) {} return "Slow"; })
            .completeOnTimeout("Default", 1, TimeUnit.SECONDS).get();
        System.out.println("Timeout fallback: " + r3);
    }
    static String fetchUser() { sleep(1000); return "User"; }
    static String fetchOrders() { sleep(1000); return "Orders"; }
    static String fetchPayments() { sleep(1000); return "Payments"; }
    static void sleep(int ms) { try { Thread.sleep(ms); } catch (Exception e) {} }
}

8.2 Complete Program — Real-Time E-Commerce Page Load

import java.util.concurrent.*;
public class EcommercePageComplete {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(4);
        CompletableFuture<String> profile = CompletableFuture.supplyAsync(() -> { sleep(800); return "Profile"; }, pool);
        CompletableFuture<String> cart = CompletableFuture.supplyAsync(() -> { sleep(600); return "Cart(3)"; }, pool);
        CompletableFuture<String> offers = CompletableFuture.supplyAsync(() -> { sleep(500); return "Offers: 20% OFF"; }, pool);
        // Even if offers fail, page should load — exceptionally for that one only
        CompletableFuture<String> offersSafe = offers.exceptionally(e -> "Offers: Unavailable");
        String page = CompletableFuture.allOf(profile, cart, offersSafe)
            .thenApply(v -> String.join(" | ", profile.join(), cart.join(), offersSafe.join())).get();
        System.out.println("PAGE: " + page);
        pool.shutdown();
    }
    static void sleep(int ms) { try { Thread.sleep(ms); } catch (Exception e) {} }
}
🧑‍🏫 Expert Note: supplyAsync() without pool uses ForkJoinPool.commonPool (cores-1 threads). If you block inside (DB call), you block common pool. In production, always pass your own Executor for I/O tasks. This is a Senior answer.

⭐ LeetCode 1221 — Split a String in Balanced Strings EASY • CompletableFuture Not Needed, Stream Pattern

Shows how Stream + reduce can solve counting problems. See full solution in Collections tutorial pattern: count balance, split when balance = 0.

Chapter 9 • Advanced • Java 21 Game Changer

Virtual Threads (Java 21) + Structured Concurrency

Virtual Threads are the biggest Java change since Lambda. They let you write simple blocking code that scales to millions of concurrent tasks — without complex async code.

🏢 Non-Tech Analogy: Platform Thread = Full-time employee (expensive, needs desk, salary). You can hire 100, not 100,000. Virtual Thread = Intern / Freelancer on demand (cheap, no desk, works and leaves). You can hire 1,00,000 for a big event. Virtual threads are cheap workers for I/O tasks.

9.1 Platform Thread vs Virtual Thread — Table

Platform ThreadVirtual Thread
Managed byOSJVM
Memory~1 MB stack~Few KB, grows/shrinks
How many?Thousands (max)Millions
Best forCPU-bound (calculation)I/O-bound (DB, API, file)
Creationnew Thread()Thread.ofVirtual()

9.2 Complete Program — Platform vs Virtual (Run It)

import java.util.concurrent.*;
import java.time.*;
public class VirtualThreadsComplete {
    public static void main(String[] args) throws Exception {
        // 1) Create single Virtual Thread — same API, just ofVirtual()
        Thread vt = Thread.ofVirtual().start(() ->
            System.out.println("Virtual: " + Thread.currentThread() + " isVirtual=" + Thread.currentThread().isVirtual()));
        vt.join();

        // 2) Named Virtual Thread + Builder
        Thread vt2 = Thread.ofVirtual().name("my-virtual-1").start(() ->
            System.out.println("Named virtual: " + Thread.currentThread().getName()));
        vt2.join();

        // 3) REAL POWER: 10,000 tasks — impossible with platform threads (OOM), easy with virtual
        long start = System.currentTimeMillis();
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 10000; i++) {
                int id = i;
                executor.submit(() -> {
                    try { Thread.sleep(100); } catch (Exception e) {} // I/O wait — virtual thread parks, not blocks OS
                    if (id % 5000 == 0) System.out.println("Virtual task " + id + " done");
                });
            }
        } // executor closes, waits for all
        System.out.println("10000 virtual tasks done in " + (System.currentTimeMillis() - start) + " ms");

        // 4) Platform thread equivalent would need: Executors.newFixedThreadPool(10000) — heavy, OOM risk
        System.out.println("Rule: I/O-bound → Virtual Threads. CPU-bound → Platform pool (cores+1).");
    }
}

9.3 Complete Program — Virtual Threads for Web Server (Real-Time)

import java.util.concurrent.*;
public class VirtualWebServerComplete {
    // Simulate handling 1000 user requests, each waits 500ms for DB
    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 1000; i++) {
                int userId = i;
                executor.submit(() -> {
                    // Blocking code — simple to write, scales with virtual threads
                    String user = fetchUserFromDB(userId); // simulates DB wait 500ms
                    String orders = fetchOrders(userId);
                    if (userId % 250 == 0) System.out.println("Handled user " + userId + ": " + user + " | " + orders);
                });
            }
        }
        System.out.println("1000 requests handled in " + (System.currentTimeMillis() - start) + " ms with Virtual Threads");
        System.out.println("With platform pool of 100 threads, same would take ~5x longer (queueing).");
        System.out.println("With CompletableFuture, same would work but code is complex (callbacks). Virtual = simple + scalable.");
    }
    static String fetchUserFromDB(int id) { sleep(200); return "User-" + id; }
    static String fetchOrders(int id) { sleep(300); return "Orders-3"; }
    static void sleep(int ms) { try { Thread.sleep(ms); } catch (Exception e) {} }
}

9.4 Structured Concurrency (Preview, Java 21) — All Tasks Together

// Structured Concurrency: Run subtasks in a scope, if one fails, cancel others, wait for all.
// Requires --enable-preview in Java 21. Concept is more important than syntax for interviews.
public class StructuredConcurrencyConcept {
    public static void main(String[] args) {
        System.out.println("Concept: try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {");
        System.out.println("  Future<String> user = scope.fork(() -> fetchUser());");
        System.out.println("  Future<String> orders = scope.fork(() -> fetchOrders());");
        System.out.println("  scope.join(); // wait for all");
        System.out.println("  scope.throwIfFailed(); // if one failed, throw");
        System.out.println("}");
        System.out.println("Benefit: No leaked threads, no forgotten futures, cancellation is automatic.");
        System.out.println("Interview line: Structured Concurrency treats concurrent tasks as one unit — like a transaction.");
    }
    static String fetchUser() { return "User"; }
    static String fetchOrders() { return "Orders"; }
}
Common Mistakes with Virtual Threads: 1) Using virtual threads for CPU-bound work — no benefit, use platform pool. 2) Using synchronized + virtual threads — synchronized pins virtual thread to OS thread (blocks). Use ReentrantLock instead (does not pin). 3) Using ThreadLocal heavily — with millions of virtual threads, ThreadLocal memory explodes. Avoid ThreadLocal with virtual threads.
🗣 Interview Q: What are Virtual Threads? When to use? Answer: “Lightweight JVM-managed threads, millions can run, ideal for I/O-bound work. Write simple blocking code, get async scalability. Do not use for CPU-bound. Avoid synchronized (pinning) and ThreadLocal with virtual threads.”
Chapter 10 • Advanced • Real Systems + LeetCode Patterns

Real-Time Systems, LeetCode Patterns & Interview Plan

10.1 Real-Time System Design — Which Tool for Which Problem?

Real ProblemTool to UseWhy?
Filter + transform listStream: filter + mapReadable, one pipeline
Group users by cityCollectors.groupingByOne line, no loops
Handle null safelyOptionalNo NPE, forced handling
API DTORecordImmutable, 1 line, no boilerplate
Different payment typesSealed + Pattern MatchingExhaustive, compiler checks
Fetch 3 APIs in parallelCompletableFuture.allOfParallel, combine, fallback
Handle 10k concurrent usersVirtual ThreadsMillions of threads, simple code
Top K frequentStream + HeapO(n log k)

10.2 LeetCode Patterns — The 6 Patterns That Solve 80% of Stream/Lambda Problems

PatternToolLeetCode
Filter + MapStreamFilter numbers, transform strings
Grouping + CountinggroupingBy + countingGroup Anagrams (49), Top K Frequent (347)
Sliding Window + MapHashMap + StreamLongest Substring (3), Min Window (76)
Heap for Top KPriorityQueueKth Largest (215), Top K (347)
Stack for MatchingArrayDequeValid Parentheses (20), Daily Temperatures (739)
Two Pointers + SortArrays.sort + Lambda3Sum (15), Sort by Frequency (1636)

⭐ LeetCode 3 — Longest Substring Without Repeating Characters MEDIUM • Stream + HashMap + Sliding Window

import java.util.*;
public class LongestSubstring {
    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> lastSeen = new HashMap<>();
        int max = 0, start = 0;
        for (int end = 0; end < s.length(); end++) {
            char c = s.charAt(end);
            if (lastSeen.containsKey(c)) start = Math.max(start, lastSeen.get(c) + 1);
            lastSeen.put(c, end);
            max = Math.max(max, end - start + 1);
        }
        return max;
    }
    public static void main(String[] args) {
        System.out.println(new LongestSubstring().lengthOfLongestSubstring("abcabcbb")); // 3
        System.out.println(new LongestSubstring().lengthOfLongestSubstring("pwwkew")); // 3
    }
}

Step-by-step for “abcabcbb”: end=0 a → window [0,0] len1 max1. end=1 b → [0,1] len2 max2. end=2 c → [0,2] len3 max3. end=3 a seen at 0 → start=1 → window [1,3] “bca” len3. end=4 b seen at1 → start=2 → [2,4] “cab” len3. Continue → max stays 3.

⭐ LeetCode 15 — 3Sum MEDIUM • Sorting + Two Pointers + Lambda

import java.util.*;
public class ThreeSum {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i-1]) continue; // skip duplicate i
            int l = i + 1, r = nums.length - 1;
            while (l < r) {
                int sum = nums[i] + nums[l] + nums[r];
                if (sum == 0) {
                    res.add(List.of(nums[i], nums[l], nums[r]));
                    while (l < r && nums[l] == nums[l+1]) l++;
                    while (l < r && nums[r] == nums[r-1]) r--;
                    l++; r--;
                } else if (sum < 0) l++; else r--;
            }
        }
        return res;
    }
    public static void main(String[] args) {
        System.out.println(new ThreeSum().threeSum(new int[]{-1,0,1,2,-1,-4}));
    }
}

⭐ LeetCode 11 — Container With Most Water MEDIUM • Two Pointers

public class ContainerWater {
    public int maxArea(int[] height) {
        int l = 0, r = height.length - 1, max = 0;
        while (l < r) {
            int area = Math.min(height[l], height[r]) * (r - l);
            max = Math.max(max, area);
            if (height[l] < height[r]) l++; else r--; // move shorter side — taller side cannot increase area
        }
        return max;
    }
    public static void main(String[] args) {
        System.out.println(new ContainerWater().maxArea(new int[]{1,8,6,2,5,4,8,3,7})); // 49
    }
}

Why move shorter side? Area = min(height) × width. Width only shrinks as pointers move. If you move taller side, min stays same or drops, width drops → area cannot increase. Moving shorter side is the only chance to increase min.

⭐ LeetCode 739 — Daily Temperatures MEDIUM • Stack + Monotonic Pattern

import java.util.*;
public class DailyTemperatures {
    public int[] dailyTemperatures(int[] temps) {
        int[] res = new int[temps.length];
        Deque<Integer> stack = new ArrayDeque<>(); // stores indices, decreasing temps
        for (int i = 0; i < temps.length; i++) {
            while (!stack.isEmpty() && temps[i] > temps[stack.peek()]) {
                int prev = stack.pop();
                res[prev] = i - prev; // days to wait for warmer temp
            }
            stack.push(i);
        }
        return res; // remaining in stack = 0 (no warmer day)
    }
    public static void main(String[] args) {
        System.out.println(Arrays.toString(new DailyTemperatures().dailyTemperatures(new int[]{73,74,75,71,69,72,76,73}))); // [1,1,4,2,1,1,0,0]
    }
}

⭐ LeetCode 20 — Valid Parentheses EASY • Stack + Map

import java.util.*;
public class ValidParentheses {
    public boolean isValid(String s) {
        Deque<Character> stack = new ArrayDeque<>();
        Map<Character, Character> pairs = Map.of(')', '(', '}', '{', ']', '[');
        for (char c : s.toCharArray()) {
            if (pairs.containsValue(c)) stack.push(c);
            else if (stack.isEmpty() || stack.pop() != pairs.get(c)) return false;
        }
        return stack.isEmpty();
    }
    public static void main(String[] args) {
        System.out.println(new ValidParentheses().isValid("()[]{}")); // true
        System.out.println(new ValidParentheses().isValid("(]")); // false
    }
}

10.3 Common Mistakes Interviewers Catch

10.4 Rapid-Fire Revision — Speak in 10 Seconds Each

QuestionOne-Line Answer
What is Lambda?Anonymous function, implementation of Functional Interface, passes behaviour.
Functional Interface?Interface with exactly one abstract method. Example: Runnable, Predicate.
Predicate vs Function vs Consumer vs Supplier?Predicate: T→boolean. Function: T→R. Consumer: T→void. Supplier: void→T.
Stream vs Collection?Collection = storage. Stream = pipeline to process, single-use, lazy.
Intermediate vs Terminal?Intermediate = lazy (filter, map). Terminal = eager (collect, forEach, count).
map vs flatMap?map: 1→1. flatMap: 1→many + flatten.
Optional orElse vs orElseGet?orElse = eager (always runs). orElseGet = lazy (only if empty).
Record vs Class?Record = immutable, auto equals/hashCode/toString. Class = mutable, full control.
Virtual vs Platform Thread?Virtual = JVM, lightweight, millions, I/O. Platform = OS, heavy, thousands, CPU.
thenApply vs thenCompose vs thenCombine?thenApply = transform. thenCompose = chain futures. thenCombine = combine 2 futures.

10.5 7-Day Practice Plan — For All Ages

Day 1: Lambda + Functional Interfaces
Day 2: Stream Intermediate + Terminal
Day 3: Collectors + Grouping
Day 4: Optional + Records
Day 5: CompletableFuture + Pattern Matching
Day 6: Virtual Threads + LeetCode (3, 15, 20)
Day 7: Mock — 1 Stream + 1 Virtual Thread + 10 Rapid-Fire
Final Interview Tip: After solving any Stream/Lambda problem, always say: “Time O(...), Space O(...), Edge cases: empty list, null, single element, duplicates.” Interviewers note this as Senior mindset.

❓ Q&A — Questions Students Ask

Q: Is Stream faster than loop?
A: For simple loops, loop is slightly faster (less overhead). For large data + parallel, Stream is faster. Use Stream for readability, not for micro-speed. For CPU-heavy large data, use parallelStream.

Q: Can Lambda be used for all interfaces?
A: No, only Functional Interfaces (one abstract method). If interface has 2 abstract methods, Lambda cannot be used — compiler cannot know which method you mean.

Q: What is the difference between forEach and map?
A: forEach = terminal, for side-effects (printing), returns void. map = intermediate, for transformation, returns new Stream.

Q: Should I use Optional for every null check?
A: No. Use Optional for return values (e.g., findUserById). Do not use for fields, parameters, or simple local null checks — plain if is clearer.

Q: Do Virtual Threads replace CompletableFuture?
A: Not fully. Virtual Threads simplify blocking code. CompletableFuture is still best for complex async pipelines (chaining, combining, timeouts). Many apps use both: Virtual Threads for request handling, CompletableFuture for parallel API calls.

⭐ Bonus — Convert Any Loop to Stream in 3 Steps (Interview Trick)

Step 1 — Old Loop:
List<String> result = new ArrayList<>();
for (Student s : students) {
    if (s.marks > 80) result.add(s.name.toUpperCase());
}
Step 2 — Identify: Source = students. Filter = marks > 80. Map = name.toUpperCase(). Collect = toList.
Step 3 — New Stream:
List<String> result = students.stream()
    .filter(s -> s.marks > 80)
    .map(s -> s.name.toUpperCase())
    .toList();

Practice this conversion for 10 loops, and you will convert any loop to Stream in interviews in 10 seconds.

🧑‍💼 For Non-Tech Readers — One Paragraph Summary:
Modern Java lets developers write less code that is easier to read and harder to break. Lambda is a shortcut for “do this”. Stream is an assembly line for data. Optional is a safety box for “might be empty”. Virtual Threads are cheap workers that let one server handle millions of users at once. Together, they make apps faster to build, cheaper to run, and less likely to crash.