Lambdas and functional interfaces
A functional interface has exactly one abstract method (@FunctionalInterface makes the compiler check). A lambda is a short way to implement it; a method reference is shorter still when a method already does the job.
Comparator<String> byLength = (a, b) -> Integer.compare(a.length(), b.length());Function<String, Integer> len = String::length; // method referenceSupplier<List<String>> fresh = ArrayList::new; // constructor referencePredicate<String> empty = String::isEmpty;Consumer<String> print = System.out::println;
| Interface | Method | Shape |
|---|---|---|
Function<T,R> | apply | T → R |
Predicate<T> | test | T → boolean |
Consumer<T> | accept | T → void |
Supplier<T> | get | () → T |
UnaryOperator<T> / BinaryOperator<T> | apply | T → T / (T, T) → T |
Lambdas can only use local variables that are effectively final (never reassigned after initialization).
Streams
A stream is a pipeline over data: a source, any number of intermediate operations (lazy: filter, map, sorted, distinct), and one terminal operation (collect, count, forEach, reduce) that actually runs it. A stream can be consumed only once.
record Emp(String name, String dept, double salary) {}List<String> richNames = emps.stream().filter(e -> e.salary() > 100_000).map(Emp::name).sorted().toList(); // Java 16+Map<String, Double> avgByDept = emps.stream().collect(Collectors.groupingBy(Emp::dept, Collectors.averagingDouble(Emp::salary)));Optional<Emp> top = emps.stream().max(Comparator.comparingDouble(Emp::salary));int total = IntStream.rangeClosed(1, 100).sum(); // primitive stream, no boxing
mapturns each element into one element;flatMapturns each into a stream and flattens them.- Short-circuiting ops (
findFirst,anyMatch,limit) stop early. parallelStream()splits work across the common ForkJoin pool: only worth it for large, CPU-bound, side-effect-free work.
Optional
Optional<T> makes "there may be no value" explicit in a return type, instead of returning null.
Optional<User> user = repo.findByEmail(email);String name = user.map(User::name).orElse("guest");user.ifPresent(u -> mailer.welcome(u));User u = user.orElseThrow(() -> new NotFoundException(email));
Use Optional for return values. Avoid it for fields, parameters or collections (return an empty list instead), and never call get() without checking.
Modern Java: records, var, switch, sealed, text blocks
record Money(String currency, long cents) { // Java 16: immutable data carrierMoney { if (cents < 0) throw new IllegalArgumentException(); } // compact constructor}var items = new ArrayList<String>(); // Java 10: local type inferenceString kind = switch (day) { // Java 14: switch expressioncase SATURDAY, SUNDAY -> "weekend";default -> "weekday";};sealed interface Shape permits Circle, Square {} // Java 17: closed hierarchyrecord Circle(double r) implements Shape {}record Square(double side) implements Shape {}double area = switch (shape) { // Java 21: pattern matching for switchcase Circle c -> Math.PI * c.r() * c.r();case Square s -> s.side() * s.side();}; // no default needed: sealedString json = """{ "name": "Ada" }"""; // Java 15: text block
Interview questions
Try answering out loud first, then open the model answer.
Q1What is a functional interface? Name some built-in ones.beginner
An interface with exactly one abstract method, so it can be implemented by a lambda. Built-ins: Runnable, Comparator, Function, Predicate, Consumer, Supplier, BiFunction. It may still have default and static methods.
Q2Intermediate vs terminal stream operations?beginner
Intermediate operations (filter, map, sorted) return a new stream and are lazy: nothing runs until a terminal operation (collect, forEach, count, reduce) is called. After the terminal operation the stream is consumed.
Q3map vs flatMap?intermediate
map transforms each element into exactly one element. flatMap transforms each element into a stream and concatenates them, e.g. sentences.stream().flatMap(s -> Arrays.stream(s.split(" "))) gives all words.
Q4How do you group a list of employees by department and count them?intermediate
Map<String, Long> counts = emps.stream().collect(Collectors.groupingBy(Emp::dept, Collectors.counting()));
Q5Why use Optional and what are common misuses?intermediate
It makes absence explicit in an API and offers fluent handling (map, orElse, orElseThrow). Misuses: calling get() without checking, using it for fields or parameters, wrapping collections, or Optional.of(null) (use ofNullable).
Q6What is a record?intermediate
A concise immutable data class (Java 16). record Point(int x, int y) {} generates private final fields, a canonical constructor, accessors x()/y(), and equals, hashCode, toString. Records can't extend classes but can implement interfaces and add methods.
Q7When should you use parallel streams?advanced
Only for large datasets with CPU-heavy, independent, side-effect-free work and sources that split well (arrays, ArrayList, ranges). They share the common ForkJoin pool, so blocking I/O in them hurts the whole app. Measure first.
Q8What are default methods and why were they added?intermediate
Interface methods with a body. They let Java 8 add methods like forEach and stream() to existing interfaces such as Collection without breaking every class that implements them. If two interfaces supply the same default method, the class must override it.
Quick check
0 of 4 answered