A lambda expression is a concise way to represent an implementation of a functional interface's single abstract method, using the arrow (->) syntax instead of an anonymous class. It lets you pass behavior as a value.
Key Points: • A lambda has the form (parameters) -> expression or (parameters) -> { statements }. • It can only be used where a functional interface (one abstract method) is expected, such as Runnable, Comparator, or Predicate. • Lambdas remove the boilerplate of anonymous inner classes, making code shorter and easier to read. • They enable a functional programming style, which pairs naturally with the Stream API for filtering, mapping, and reducing data. • Lambdas can capture final or effectively final variables from their enclosing scope.
Example: Instead of writing an anonymous Runnable class with a run() method, you can write Runnable r = () -> System.out.println("Hello"); in a single line.
Code Example:
// Before Java 8
Comparator<String> byLength = new Comparator<String>() {
public int compare(String a, String b) {
return a.length() - b.length();
}
};
// With a lambda
Comparator<String> byLengthLambda = (a, b) -> a.length() - b.length();Interview Tip: A concise interview answer is:
"A lambda expression is a compact way to implement a functional interface's single method inline, without the boilerplate of an anonymous class. It improves readability, reduces code, and enables functional-style programming, which is especially useful with the Stream API and other APIs that take behavior as a parameter."