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.
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.
| Word | Simple Meaning | Example |
|---|---|---|
| Lambda | Function as value — pass behaviour, not just data. | list.forEach(x -> System.out.println(x)) |
| Stream | Pipeline to process data — filter, transform, collect. | list.stream().filter(...).map(...).toList() |
| Optional | Box that may be empty — forces you to handle “no value”. | Optional.ofNullable(user).orElse("Guest") |
| Virtual Thread | Lightweight thread — millions can run at once. | Thread.ofVirtual().start(task) |
Old Java was verbose. Modern Java is expressive. Same program in 30 lines becomes 5 lines — with fewer bugs.
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();
| Version | Big Feature | One Line |
|---|---|---|
| Java 8 (2014) | Lambda, Stream, Optional, Date-Time | Birth of modern Java |
| Java 11 (2018) | var, HttpClient, String methods | LTS, production standard |
| Java 17 (2021) | Records, Sealed Classes, Pattern Matching | LTS, modern + stable |
| Java 21 (2023) | Virtual Threads, Structured Concurrency, Pattern Matching | LTS, current best |
Lambda = A function without a name, that you can pass like a value. This one idea changed Java forever.
Runnable r = new Runnable() {
public void run() {
System.out.println("Hello");
}
};
new Thread(r).start();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.
// (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;// 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
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);
}
}
int count = 0;
list.forEach(x -> count++); // COMPILE ERROR — count must be final / effectively final
// Fix: Use AtomicInteger or int[1] or Stream count()forEach is the cook — it calls your recipe for each item.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})));
}
}Lambda only works with Functional Interfaces — interfaces with exactly ONE abstract method. Learn the 4 built-in ones, and you can use Lambda everywhere.
// 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
}
}
| Interface | Method | Input → Output | Example |
|---|---|---|---|
| Predicate<T> | test(T) | T → boolean | x -> x > 18 (is adult?) |
| Function<T,R> | apply(T) | T → R | s -> s.length() (String → Integer) |
| Consumer<T> | accept(T) | T → void | s -> 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, BiConsumer | Same with 2 inputs | (T,U) → boolean / void | (a,b) -> a.equals(b) |
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
}
}
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);
}
}
s -> System.out.println(s) → System.out::println). Use Lambda when you need logic (s -> s.length() > 3). Interviewers check readability, not just correctness.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.
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).
[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.
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());
}
}
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.");
}
}
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).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.
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
}
}Collectors are the most powerful part of Streams. They can group, count, average, partition — in one line.
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);
}
}
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.");
}
}
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"}));
}
}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]
}
}NullPointerException is the #1 crash in Java. Optional forces you to handle “no value” — at compile time, not at runtime crash.
// 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
}
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"; }
}
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.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.
These 4 features remove boilerplate. A 50-line POJO becomes 1 line. A 20-line if-else chain becomes 5 lines.
// 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));
}
}
// 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
}
}
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);
}
}
Old Future blocks. CompletableFuture chains. Learn to run 3 tasks in parallel and combine — this is asked in every Senior interview.
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) {} }
}
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) {} }
}
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.Shows how Stream + reduce can solve counting problems. See full solution in Collections tutorial pattern: count balance, split when balance = 0.
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.
| Platform Thread | Virtual Thread | |
|---|---|---|
| Managed by | OS | JVM |
| Memory | ~1 MB stack | ~Few KB, grows/shrinks |
| How many? | Thousands (max) | Millions |
| Best for | CPU-bound (calculation) | I/O-bound (DB, API, file) |
| Creation | new Thread() | Thread.ofVirtual() |
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).");
}
}
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) {} }
}
// 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"; }
}
| Real Problem | Tool to Use | Why? |
|---|---|---|
| Filter + transform list | Stream: filter + map | Readable, one pipeline |
| Group users by city | Collectors.groupingBy | One line, no loops |
| Handle null safely | Optional | No NPE, forced handling |
| API DTO | Record | Immutable, 1 line, no boilerplate |
| Different payment types | Sealed + Pattern Matching | Exhaustive, compiler checks |
| Fetch 3 APIs in parallel | CompletableFuture.allOf | Parallel, combine, fallback |
| Handle 10k concurrent users | Virtual Threads | Millions of threads, simple code |
| Top K frequent | Stream + Heap | O(n log k) |
| Pattern | Tool | LeetCode |
|---|---|---|
| Filter + Map | Stream | Filter numbers, transform strings |
| Grouping + Counting | groupingBy + counting | Group Anagrams (49), Top K Frequent (347) |
| Sliding Window + Map | HashMap + Stream | Longest Substring (3), Min Window (76) |
| Heap for Top K | PriorityQueue | Kth Largest (215), Top K (347) |
| Stack for Matching | ArrayDeque | Valid Parentheses (20), Daily Temperatures (739) |
| Two Pointers + Sort | Arrays.sort + Lambda | 3Sum (15), Sort by Frequency (1636) |
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.
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}));
}
}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.
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]
}
}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
}
}Optional.get() without check — NoSuchElementException.orElse(expensive()) instead of orElseGet(() -> expensive()) — eager call.| Question | One-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. |
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.
List<String> result = new ArrayList<>();
for (Student s : students) {
if (s.marks > 80) result.add(s.name.toUpperCase());
}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.