Lambda Expressions in Java
Quick Answer
Lambda Expressions explains lambda expressions were introduced in Java 8 to enable functional programming features.
Learning Objectives
- Explain the purpose of Lambda Expressions in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Lambda Expressions.
- Apply Lambda Expressions in a simple real-world scenario or practice task.
Introduction to Lambda Expressions
Lambda expressions were introduced in Java 8 to enable functional programming features.
They provide a concise way to represent anonymous functions and simplify code, especially when working with collections and streams.
Code less, do more.
What Are Lambda Expressions?
A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions eliminate the need for anonymous class implementations.
They are primarily used to define inline implementations of functional interfaces (interfaces with a single abstract method).
- Syntax: (parameters) -> expression or (parameters) -> { statements; }
- Can be assigned to variables or passed as arguments.
- Enable functional programming style in Java.
Syntax and Components
A lambda expression consists of three parts: parameter list, arrow token (->), and body.
Parameters can be omitted if they can be inferred, and the body can be a single expression or a block of statements.
- Parameter list: zero or more comma-separated parameters.
- Arrow token: separates parameters and body.
- Body: single expression or multiple statements enclosed in braces.
| Example | Description |
|---|---|
| () -> 42 | No parameters, returns 42 |
| x -> x * x | One parameter, returns its square |
| (x, y) -> x + y | Two parameters, returns their sum |
| (x, y) -> { System.out.println(x); return y; } | Multiple statements in body |
Functional Interfaces
Lambda expressions require a target type, which must be a functional interface.
Java provides several built-in functional interfaces in the java.util.function package.
- Common interfaces: Runnable, Callable, Comparator, Consumer, Supplier, Function, Predicate.
- A functional interface has exactly one abstract method.
- You can create your own functional interfaces using @FunctionalInterface annotation.
| Interface | Method | Description |
|---|---|---|
| Runnable | void run() | No arguments, no return value |
| Supplier<T> | T get() | No arguments, returns a value |
| Consumer<T> | void accept(T t) | Takes one argument, no return |
| Function<T,R> | R apply(T t) | Takes one argument, returns a value |
| Predicate<T> |
Using Lambda Expressions in Java
Lambda expressions are commonly used with collections and streams to write concise and readable code.
They help replace verbose anonymous inner classes.
- Sorting collections with Comparator lambdas.
- Filtering and mapping streams.
- Event handling in GUI applications.
Example: Sorting a List
Here is how to sort a list of strings by length using a lambda expression.
Practical Example
This example sorts a list of strings by their length using a lambda expression as a Comparator.
This example uses a lambda expression with the filter method to select even numbers from a list.
Examples
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList("Anna", "John", "Elizabeth", "Mike");
names.sort((s1, s2) -> s1.length() - s2.length());
System.out.println(names);
}
}This example sorts a list of strings by their length using a lambda expression as a Comparator.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers);
}
}This example uses a lambda expression with the filter method to select even numbers from a list.
Best Practices
- Use lambda expressions to simplify code and improve readability.
- Prefer method references when they make the code cleaner.
- Keep lambda bodies short and focused.
- Use meaningful parameter names in lambdas for clarity.
- Avoid complex logic inside lambda expressions; extract to methods if needed.
Common Mistakes
- Using lambda expressions where a method reference would be clearer.
- Writing overly complex lambda bodies that reduce readability.
- Ignoring the functional interface requirement and trying to assign lambdas to incompatible types.
- Forgetting that lambdas cannot throw checked exceptions unless handled.
Hands-on Exercise
Create a Custom Functional Interface
Define a functional interface named 'Calculator' with a method that takes two integers and returns an integer. Then implement it using a lambda expression that adds the two numbers.
Expected output: A lambda that adds two integers and returns the sum.
Hint: Use @FunctionalInterface annotation and implement the method with a lambda.
Filter a List Using Lambda
Given a list of strings, use a lambda expression with the stream API to filter out strings shorter than 4 characters.
Expected output: A list containing only strings with length 4 or more.
Hint: Use the filter method with a Predicate lambda.
Interview Questions
What is a lambda expression in Java?
InterviewA lambda expression is a concise way to represent an anonymous function that can be passed around and executed, introduced in Java 8 to support functional programming.
What is a functional interface?
InterviewA functional interface is an interface with exactly one abstract method, which can be implemented using a lambda expression.
Can lambda expressions throw checked exceptions?
InterviewLambda expressions can throw checked exceptions only if the functional interface method declares those exceptions, and the lambda body handles or declares them accordingly.
MCQ Quiz
1. What is the primary purpose of lambda expressions introduced in Java 8?
Select one option to check your answer.
2. Which of the following is the correct syntax for a lambda expression that takes two integers and returns their sum?
Select one option to check your answer.
3. What is a functional interface in the context of lambda expressions?
Select one option to check your answer.
4. Which built-in functional interface would you use with a lambda expression that takes one argument and returns a boolean?
Select one option to check your answer.
5. Consider the following code snippet: List<String> names = Arrays.asList("Anna", "John", "Elizabeth", "Mike"); names.sort((s1, s2) -> s1.length() - s2.length()); What does this lambda expression do?
Select one option to check your answer.
Key Takeaways
- Lambda expressions were introduced in Java 8 to enable functional programming features.
- They provide a concise way to represent anonymous functions and simplify code, especially when working with collections and streams.
- A lambda expression is a short block of code which takes in parameters and returns a value.
- Lambda expressions eliminate the need for anonymous class implementations.
- They are primarily used to define inline implementations of functional interfaces (interfaces with a single abstract method).
Frequently Asked Questions
What is the main benefit of using lambda expressions?
They reduce boilerplate code and improve readability by allowing inline implementation of functional interfaces.
Are lambda expressions objects in Java?
Yes, lambda expressions are instances of functional interfaces and can be treated as objects.
Can lambda expressions access local variables?
Yes, but only if those variables are effectively final (not modified after initialization).
Summary
Lambda expressions are a powerful feature introduced in Java 8 that enable functional programming.
They allow you to write concise and readable code by representing anonymous functions inline.
Understanding lambda syntax, functional interfaces, and common use cases is essential for modern Java development.





