Day 5 · 1 Hour
Advanced Java
Streams, Lambdas, Optional — the tools that separate junior devs from senior devs.
🔥 Real-World Hook (0–5 min)
Netflix shows you 200 recommended movies filtered from 10,000 — in under a second. How?
Not a manual for-loop. They use Java Streams — a pipeline that filters, transforms, and collects data in one fluent chain. Today you learn the tools that separate junior devs from senior devs.
⚙ Streams — Factory Assembly Line (5–20 min)
💡 Analogy
Raw materials (data) enter at one end. Each station (filter, map, sort) does one thing. Finished products (result) come out the other end. Stations don't know about each other — they just do their job.
💻 Live Coding — Student Pipeline (20–40 min)
import java.util.*; import java.util.stream.*; record Student(String name, int marks, String dept) {} public class StreamDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Priya", 92, "CS"), new Student("Ravi", 45, "IT"), new Student("Anita", 78, "CS"), new Student("Meena", 88, "CS") ); // CS students who passed, sorted by marks desc List<String> result = students.stream() .filter(s -> s.dept().equals("CS")) .filter(s -> s.marks() >= 60) .sorted((a,b) -> b.marks() - a.marks()) .map(Student::name) .collect(Collectors.toList()); System.out.println(result); // [Meena, Anita, Priya] double avg = students.stream() .mapToInt(Student::marks).average().orElse(0); System.out.println("Avg: " + avg); } }
🛡 Optional — Never NullPointerException Again
// Safe with Optional: Optional<User> user = repo.findById(id); user.ifPresent(u -> System.out.println(u.getName())); String name = user.map(User::getName).orElse("Unknown"); User u = user.orElseThrow(() -> new RuntimeException("Not found"));
🎯 You Code It (40–55 min)
- Create a
Productrecord: name, price (double), inStock (boolean), category (String) - Add 8 products: mix of Electronics/Clothing, in-stock/out-of-stock, prices ₹200–₹5000
- Use streams: filter in-stock only, then filter Electronics, sort by price ascending
- Get the top 3 cheapest in-stock Electronics as a List of names
- Calculate total value of all in-stock products using
mapToDouble().sum() - Show: Print names list and total value
📄 Day 5 Cheat Sheet — Advanced Java
Stream Pipeline
| list.stream() | Start stream |
| .filter(x -> cond) | Keep matching |
| .map(x -> transform) | Transform each |
| .sorted(comparator) | Sort |
| .limit(n) | First n items |
| .collect(toList()) | End to list |
Stream Terminals
| .count() | Count items |
| .findFirst() | First Optional |
| .anyMatch(pred) | At least one? |
| .mapToInt().sum() | Sum ints |
| .mapToDouble().average() | Average |
| Collectors.joining(", ") | Join to String |
Optional
| Optional.of(value) | Wrap value |
| Optional.empty() | Empty optional |
| opt.isPresent() | Has value? |
| opt.orElse(default) | Safe get |
| opt.orElseThrow() | Throw if empty |
| opt.map(fn) | Transform if present |
Exceptions
| try { } catch(E e) { } | Handle error |
| finally { } | Always runs |
| throw new RuntimeException() | Throw |
| class MyEx extends RuntimeException | Custom |
| e.getMessage() | Error text |