What is a lambda expression in Java and where can you use it?
A lambda is a short anonymous function written as (parameters) -> body. It can be used wherever a functional interface, an interface with exactly one abstract method, is expected, such as Runnable, Comparator or Predicate.
Explain it simply
Instead of hiring a full-time employee to do one tiny job, a lambda is a sticky note with the instruction: "take two numbers and add them". You hand the note to whoever needs it.
Example
import java.util.*;
import java.util.function.*;
BinaryOperator<Integer> add = (a, b) -> a + b;
System.out.println(add.apply(3, 4)); // prints: 7
List<String> names = new ArrayList<>(List.of("Meera", "Om", "Kabir"));
names.sort((x, y) -> x.length() - y.length());
System.out.println(names); // prints: [Om, Meera, Kabir]
Runnable r = () -> System.out.println("hello");
r.run(); // prints: helloWhat to say in the interview
"A lambda implements the single abstract method of a functional interface, and the compiler infers the types from context. It replaces verbose anonymous inner classes. A lambda can use local variables from its surroundings only if they are final or effectively final, because it captures their values. Inside a lambda, this refers to the enclosing class, unlike an anonymous class where this is the anonymous object."
Common mistakes
- Modifying a local variable from inside a lambda. It will not compile.
- Thinking a lambda is always faster than an anonymous class. It is mainly shorter and clearer.