Lambdas: compact objects with one job
A lambda is a function-shaped object
A lambda expression is a very concise way to produce an instance of a single-abstract-method interface — Runnable, Callable, Comparator, Consumer, Predicate, or your own @FunctionalInterface. The compiler handles the boilerplate; you supply the body.
Comparator<String> byLen = (a, b) -> Integer.compare(a.length(), b.length());
// Captured locals must be effectively final
String prefix = "user:";
Function<Integer, String> id = n -> prefix + n;
// Method references are the shorthand form
list.sort(Comparator.comparingInt(String::length));Effective final — why the compiler cares
A lambda captures local variables. If those variables could change after the lambda was created, the lambda's behavior would depend on timing — a hostile foot-gun, especially once the lambda runs on another thread. Java rules out this bug class by requiring captured locals to be effectively final (assigned exactly once).
Takeaways
- Lambdas are syntactic sugar for implementing single-abstract-method interfaces.
- Captured locals must be effectively final.
- Method references read better when the lambda is a simple delegation.
Enjoying This Lesson?
Your support helps create more comprehensive courses and lessons like this one. Help me build better learning experiences for everyone.
Support Awashyak