A lambda expression is a short way to write an implementation of a functional interface. Lambda expressions were introduced in Java 8 and are commonly used with collections, event handling, and functional programming.
A lambda expression allows you to provide the behavior of a method without writing a separate implementation class.
Syntax:
(parameters) -> expression
Example:
public class Main {
public static void main(String[] args) {
Runnable task = () -> System.out.println("Hello Java");
task.run();
}
}
Hello Java
The () represents the parameters,
-> is the lambda operator, and the
statement after it is the task to execute.
If a lambda expression has one parameter, parentheses around the parameter can be omitted when its type is inferred.
interface Greeting {
void sayHello(String name);
}
public class Main {
public static void main(String[] args) {
Greeting g = name ->
System.out.println("Hello " + name);
g.sayHello("Rahul");
}
}
Hello Rahul
Here, name is the parameter passed to
the lambda expression.
A lambda expression can accept multiple parameters. Separate them with commas.
interface Calculator {
int add(int a, int b);
}
public class Main {
public static void main(String[] args) {
Calculator c = (a, b) -> a + b;
System.out.println(c.add(10, 20));
}
}
30
The lambda receives two numbers and returns their sum.
Use curly braces when a lambda expression contains multiple statements. If the lambda returns a value, use an appropriate return statement.
interface Calculator {
int calculate(int a, int b);
}
public class Main {
public static void main(String[] args) {
Calculator c = (a, b) -> {
int result = a + b;
return result;
};
System.out.println(c.calculate(15, 5));
}
}
20
A functional interface is an interface with exactly one abstract method. It can be implemented using a lambda expression.
@FunctionalInterface
interface Message {
void show();
}
public class Main {
public static void main(String[] args) {
Message m = () -> System.out.println("Welcome to Java");
m.show();
}
}
Welcome to Java
The @FunctionalInterface annotation asks
the compiler to check that the interface follows the
functional-interface rules.
The forEach() method can use a lambda
expression to perform an action for each item in a list.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List names = Arrays.asList(
"Amit", "Rahul", "Priya"
);
names.forEach(name -> System.out.println(name));
}
}
Amit
Rahul
Priya
The lambda executes once for each name in the list.
Lambda expressions can perform calculations through functional interfaces.
@FunctionalInterface
interface Square {
int calculate(int number);
}
public class Main {
public static void main(String[] args) {
Square s = n -> n * n;
System.out.println(s.calculate(5));
System.out.println(s.calculate(8));
}
}
25
64
Lambda expressions can be used with
sort() to define custom sorting behavior.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List numbers = new ArrayList<>(
Arrays.asList(40, 10, 30, 20)
);
numbers.sort((a, b) -> a - b);
System.out.println(numbers);
}
}
[10, 20, 30, 40]
The lambda compares two numbers to define their order.
For general-purpose sorting, prefer
Integer.compare(a, b) instead of subtraction
to avoid integer-overflow issues.
numbers.sort((a, b) -> Integer.compare(a, b));
The Predicate functional interface represents
a condition that returns true or false.
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate isEven = n -> n % 2 == 0;
System.out.println(isEven.test(10));
System.out.println(isEven.test(7));
}
}
true
false
The test() method checks whether the
supplied number satisfies the condition.
The Function interface accepts one input
and produces a result.
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function getLength =
text -> text.length();
System.out.println(getLength.apply("Java"));
System.out.println(getLength.apply("Programming"));
}
}
4
11
The type parameters String and
Integer represent the input and output
types respectively.
The Consumer interface accepts a value
and performs an action without returning a result.
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Consumer printMessage =
message -> System.out.println(message);
printMessage.accept("Learning Lambda Expressions");
}
}
Learning Lambda Expressions
The accept() method executes the action
defined by the lambda expression.
| Lambda Expression | Traditional Implementation |
|---|---|
| Usually requires less code. | May require a separate class or anonymous class. |
Uses the -> operator. |
Uses a method implementation. |
| Works with functional interfaces. | Can implement interfaces using classes. |
| Useful for short behavior definitions. | Useful for larger or reusable implementations. |
interface Greeting {
void sayHello();
}
class MyGreeting implements Greeting {
public void sayHello() {
System.out.println("Hello");
}
}
public class Main {
public static void main(String[] args) {
Greeting g = new MyGreeting();
g.sayHello();
}
}
interface Greeting {
void sayHello();
}
public class Main {
public static void main(String[] args) {
Greeting g = () -> System.out.println("Hello");
g.sayHello();
}
}
Hello
forEach() to print all elements of a list.Predicate to check whether a number is positive.Function to convert a string to uppercase.Consumer to print each student's name.Select the correct answer for each question.