Nearby lessons

90 of 125

Java - Lambda Expressions

📌 What You Will Learn
  • Lambda expressions — the big change
  • Functional interfaces
  • Default and static methods in interfaces
  • The four workhorses: Predicate, Function, Consumer, Supplier
  • Method references (::)
  • The Stream API for processing collections
  • Optional — safe null handling
  • The new Date and Time API

Lambda Expressions is a core concept of the Java language. This lesson explains Lambda Expressions with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Lambda Expressions

A lambda expression is a short way to write a function without a name. It is like passing a behaviour as a value.

Look at the difference — the lambda keeps only the parameters and the logic. The structure:

Example01
JCode Cell
1// Normal way: a whole anonymous class for one method
2Comparator<String> c1 = new Comparator<String>() {
3 public int compare(String a, String b) {
4 return a.length() - b.length();
5 }
6};
7 
8// Lambda way: only the important part
9Comparator<String> c2 = (a, b) -> a.length() - b.length();

Lambda Expressions

Example02
JCode Cell
1(parameters) -> expression_or_body
2 
3(a, b) -> a + b // two params, returns a + b
4x -> x * 2 // one param (brackets optional)
5() -> System.out.println("hi") // no params

Lambda Expressions

In simple words: A lambda is a nameless function that keeps only the parameters and the logic. Everything else — the class name, the method name, the return type — is dropped, so the code becomes much shorter.
Example03
JCode Cell
1import java.util.*;
2 
3class LambdaDemo {
4 public static void main(String[] args) {
5 List<String> names = new ArrayList<>(List.of("Priya", "Anil", "Rahul"));
6 
7 names.sort((a, b) -> a.compareTo(b)); // sort alphabetically
8 System.out.println(names);
9 
10 names.forEach(name -> System.out.println("Hello " + name));
11 }
12}
Output
[Anil, Priya, Rahul] Hello Anil Hello Priya Hello Rahul
📝 Key Takeaways
  • Lambda = a function without a name; (params) -> logic.
  • Functional interface = one abstract method, so a lambda can implement it.
  • Interfaces now have default and static methods with bodies.
  • Predicate (test), Function (apply), Consumer (accept), Supplier (get) are the four core functional interfaces.
  • Method references (::) are shorthand for lambdas.
  • Streams process collections with filter/map/sorted/collect pipelines.
  • Optional prevents NullPointerException with orElse/isPresent.
  • java.time (LocalDate, LocalDateTime) replaces the old Date/Calendar cleanly.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1