Lambda expressions, added in Java 8, let you write short pieces of behaviour inline instead of creating a whole class. Modern Java code, Spring Boot included, uses them everywhere, so freshers are expected to read and write them comfortably.
The syntax
(parameters) -> expression
Examples:
x -> x * 2takes x and returns double its value.(a, b) -> a + badds two values.() -> System.out.println("Hi")takes nothing and prints.
For more than one statement, use braces and an explicit return.
Before and after
Sorting a list of names by length used to need an anonymous class of several lines. With a lambda:
names.sort((a, b) -> Integer.compare(a.length(), b.length()));
Functional interfaces
A lambda can be used wherever Java expects a functional interface: an interface with exactly one abstract method. Common ones in java.util.function:
Predicate<T>: takes a value, returns true or false (used for filtering).Function<T, R>: takes a value, returns a transformed value.Consumer<T>: takes a value, returns nothing (used for printing or saving).Supplier<T>: takes nothing, returns a value.
Method references
When a lambda only calls an existing method, a method reference is shorter: names.forEach(System.out::println) instead of names.forEach(n -> System.out.println(n)).
Rules worth knowing
- A lambda can use local variables from the surrounding method only if they are effectively final (never reassigned).
- Keep lambdas short. If one grows past a few lines, move the logic into a named method and use a method reference.
Lambdas are the foundation of the Stream API: read Java streams: filter, map and collect next.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
