A lambda expression consists of a parameter list, an arrow operator (->
), and a body. The body can be a single expression or a block of statements, which implements the single abstract method of the functional interface. In this post, we are going to see Java 8 Lambda Expressions Examples.
We can also say Java 8 lambda expression is an anonymous method that doesn’t have any name, also it doesn’t have a return type and any modifier.
Note – Without Functional Interface we can’t use a lambda interface.
Program to print “Hello” using Java 8 lambda expression.
package com.javatute.java8;
@FunctionalInterface
interface I1 {
void printHello();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
I1 i1 = () -> System.out.println("Hello");
i1.printHello();
}
}
Output:-
Hello
Even to print Hello using lambda expression we need functional interface.
Syntax for lambda expression
(lambda-arguments) -> {lambda body}
- (lambda-arguments) – we can have one or multiple arguments or it can be empty.
- ->(arrow) – This links (lambda-arguments) and {body}.
- {lambda body} – Here we have core logic.
Let’s see a few examples related to the lambda expression. For better understanding, these examples have been written with and without Java 8.
Example 1 – Square of the number. Without using Java 8.
interface i5 {
public int squreOfNumber(int i);
}
public class SqureOfNumber implements i5 {
@Override
public int squreOfNumber(int i) {
return i * i;
}
public static void main(String[] args) {
SqureOfNumber number = new SqureOfNumber();
System.out.println(number.squreOfNumber(10));
}
}
Output is:-
100
With Java 8 lambda expression
interface I6 {
public int squreOfNumber(int i);
}
public class SqureOfNoUsingLambda {
public static void main(String[] args) {
I6 i6 = (i) -> i * i;
System.out.println(i6.squreOfNumber(10));
}
}
Output:-
100
Example 2 – Sum of two numbers. Without using java 8.
interface I4 {
public void sumOfTwoNumber(int n1, int n2);
}
public class SumOfTwoNumWithoutLambda implements I4 {
@Override
public void sumOfTwoNumber(int n1, int n2) {
System.out.println("Sum of n1 and n2 is:- " + (n1 + n2));
}
public static void main(String[] args) {
SumOfTwoNumWithoutLambda withoutLambda = new SumOfTwoNumWithoutLambda();
withoutLambda.sumOfTwoNumber(20, 30);
}
}
Output is:-
Sum of n1 and n2 is:- 50
Using lambda expression. Here we will see the program having two parameters in the lambda expression.
@FunctionalInterface
interface I3 {
public void sumOfTwoNumber(int n1, int n2);
}
public class LambdaExample2 {
public static void main(String[] args) {
I3 i3 = (n1, n2) -> System.out.println("Sum of n1 and n2 is:- "+ (n1 + n2));
i3.sumOfTwoNumber(20, 30);
}
}
Output is:-
Sum of n1 and n2 is:- 50
Example 3 – In this example, we will see how to write a return statement in the lambda expression.
@FunctionalInterface
interface I6 {
public int m1(int i);
}
public class SqureOfNoUsingLambda {
public static void main(String[] args) {
I6 i6 = (i) -> {
return i * i;
};
System.out.println(i6.m1(10));
}
}
Output is:-
100
Some more examples that demonstrate how to use a lambda expression
1. Simple Lambda Expression
public class SimpleLambda {
public static void main(String[] args) {
Runnable greet = () -> System.out.println("Hello, Lambda!");
greet.run();
}
}
Output:-
Hello, Lambda!
This program demonstrates the basic use of a lambda expression to create a Runnable
instance that prints “Hello, Lambda!” when executed.
2. Lambda Expression with Parameter
interface MathOperation {
int operate(int a);
}
public class LambdaWithParameter {
public static void main(String[] args) {
// Lambda expression with one parameter
MathOperation square = a -> a * a;
System.out.println("Square of 5: " + square.operate(5));
}
}
Output:-
Square of 5: 25
Here, a functional interface MathOperation
is defined with a single parameter. The lambda expression a -> a * a
implements squaring a number. The program then uses this lambda to calculate and print the square of 5.
3. Lambda Expression with Multiple Parameters
interface MathOperation {
int operate(int a, int b);
}
public class LambdaWithMultipleParameters {
public static void main(String[] args) {
// Lambda expression with multiple parameters
MathOperation addition = (a, b) -> a + b;
System.out.println("Sum of 5 and 3: " + addition.operate(5, 3));
}
}
Output:-
Sum of 5 and 3: 8
Similar to the previous program, but the functional interface MathOperation
now takes two parameters. The lambda expression (a, b) -> a + b
implements addition. The program calculates and prints the sum of 5 and 3.
4. Lambda Expression with Functional Interface
import java.util.function.Function;
public class FunctionalInterfaceLambda {
public static void main(String[] args) {
Function<Integer, Integer> doubleIt = x -> x * 2;
System.out.println("Double of 7: " + doubleIt.apply(7));
}
}
Output:-
Double of 7: 14
This program uses the built-in Function
functional interface from the java.util.function
package. A lambda expression x -> x * 2
defines a function that doubles the input. The program demonstrates applying this function to the number 7 and prints the result.
5. Lambda Expression with List Filtering
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ListFilterLambda {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 10, 15, 20, 25);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println("Even numbers: " + evenNumbers);
}
}
Output:-
Even numbers: [10, 20]
In this program, a list of integers is filtered using a lambda expression n -> n % 2 == 0
to keep only the even numbers. The resulting even numbers are collected and printed.
6. Lambda Expression with Map Transformation
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ListMapLambda {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry");
List<String> uppercased = words.stream()
.map(word -> word.toUpperCase())
.collect(Collectors.toList());
System.out.println("Uppercased words: " + uppercased);
}
}
Output:-
Uppercased words: [APPLE, BANANA, CHERRY]
A list of strings is transformed using a lambda expression word -> word.toUpperCase()
to convert each string to uppercase. The transformed words are collected and printed.
7. Lambda Expression with Thread Creation
public class ThreadLambda {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread is running.");
});
thread.start();
}
}
Output:-
Thread is running.
Here, a new thread is created using a lambda expression as the thread’s run()
method implementation. When started, the thread prints “Thread is running.”
8. Lambda Expression Capturing Local Variables
interface MathOperation {
int operate(int x);
}
public class CapturingVariables {
public static void main(String[] args) {
int multiplier = 3;
MathOperation multiplyByMultiplier = x -> x * multiplier;
System.out.println("Result: " + multiplyByMultiplier.operate(5));
}
}
Output:-
Result: 15
This program demonstrates how a lambda expression can capture and use a local variable (multiplier
). The lambda x -> x * multiplier
multiplies its input by the captured multiplier. The result is printed.
9. Lambda Expression for List Sorting
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListSortingLambda {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie"));
names.sort((name1, name2) -> name1.compareTo(name2));
System.out.println("Sorted names: " + names);
}
}
Output:-
Sorted names: [Alice, Bob, Charlie]
A list of strings is sorted using a lambda expression to compare the strings ((name1, name2) -> name1.compareTo(name2)
). The sorted names are printed.
10. Lambda Expression for Custom Sorting
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class CustomSortingLambda {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Apple");
names.add("Banana");
names.add("Cherry");
names.sort(Comparator.comparingInt(String::length));
System.out.println("Sorted names by length: " + names);
}
}
Output:-
Sorted names by length: [Apple, Banana, Cherry]
This program demonstrates sorting a list of strings based on their length. A comparator is created using a lambda expression that compares strings based on their length. The list is then sorted using this comparator, and the sorted names are printed.
These examples cover various use cases of lambda expressions in Java 8, from basic printing to more complex operations like filtering, mapping, sorting, and functional interfaces.
See docs.
Important points related to Java 8 lambda expressions.
- If we have only one line or statement in the body, curly braces are optional.
- (lambda-arguments) – It can have any number of arguments.
- If we use the return keyword, curly braces are mandatory.
- To call lambda expression we must use a Functional interface(contains a single abstract method ).
- A Functional interface can contain a single abstract method and any number of static or default method(these methods as we must have a body as we can have a method body in the interface, Java 8 onwards).
- Runnable and Comparable interfaces are examples of the Functional interface.
- We use @FunctionalInterface annotation to define a functional interface, although this is optional.
Let’s see a few objective questions related to Java 8 lambda expression.
- Which one is true regarding lambda expression in Java?
a) A no named method
b) An anonymous class
c) A functional interface
d) A data type - Which version of Java introduced lambda expressions?
a) Java 6
b) Java 7
c) Java 8
d) Java 9 - Which functional interface is commonly used with lambda expressions to represent a single parameterless operation?
a) Supplier
b) Consumer
c) Function
d) Runnable - Which symbol is used to separate the lambda parameters from the lambda body?
a) ->
b) ::
c) =>
d) – - Lambda expressions are most suitable for which type of operations?
a) Long-running tasks
b) Multithreaded tasks
c) Short and simple tasks
d) Complex algorithmic tasks - Which of the following is NOT a valid syntax for a lambda expression?
a) (int x, int y) -> x + y
b) x, y -> x + y
c) () -> “Hello”
d) (String s) -> { return s.length(); } - Which functional interface does the
java.util.function
package provide for predicate-like operations?
a) Predicate
b) Runnable
c) Consumer
d) Supplier - In a lambda expression, which type of parameters can be inferred?
a) Primitive types only
b) Reference types only
c) Both primitive and reference types
d) None - Which method reference syntax represents an instance method?
a) ClassName::staticMethod
b) instance::methodName
c) ClassName::new
d) (parameters) -> expression - What does a lambda expression capture?
a) Local variables and method parameters that are final or effectively final
b) All local variables and method parameters
c) Only instance variables of the containing class
d) Global variables - What’s the purpose of the
@FunctionalInterface
annotation in Java?
a) It marks an interface as obsolete.
b) It enables Java to optimize method calls.
c) It ensures that an interface has only one abstract method.
d) It prevents interface inheritance. - Which method of the
java.util.function.Function
interface takes an argument and returns a result?
a) apply()
b) compute()
c) process()
d) execute() - In a lambda expression, how is the return statement represented?
a) return
b) ->return
c) =>return
d) No explicit return statement is needed - Which of the following statements about lambda expressions is true?
a) They can replace all instances of anonymous classes.
b) They can only be used with interfaces that have one abstract method.
c) They can be used as standalone methods outside of classes.
d) They can be serialized and stored in files. - What’s the result of the expression
(x, y) -> x > y ? 1 : -1
when passed as an argument to aComparator
?
a) It sorts in ascending order.
b) It sorts in descending order.
c) It throws a compile-time error.
d) It generates a runtime exception. - Which of the following is NOT a valid functional interface in Java’s
java.util.function
package?
a) IntSupplier
b) DoubleConsumer
c) StringConsumer
d) Predicate - Lambda expressions are used to implement which programming concept in Java?
a) Object-oriented programming
b) Aspect-oriented programming
c) Event-driven programming
d) Functional programming - Lambda expressions primarily aim to improve:
a) Type safety
b) Runtime performance
c) Code readability and conciseness
d) Memory management
Answers:
- b) An anonymous class
- c) Java 8
- d) Runnable
- a) ->
- c) Short and simple tasks
- b) x, y -> x + y
- a) Predicate
- c) Both primitive and reference types
- b) instance::methodName
- a) Local variables and method parameters that are final or effectively final
- c) It ensures that an interface has only one abstract method.
- a) apply()
- d) No explicit return statement is needed
- b) They can only be used with interfaces that have one abstract method.
- a) It sorts in ascending order.
- c) StringConsumer
- d) Functional programming
- c) Code readability and conciseness
That’s all about Java 8 Lambda Expressions Examples
See docs for more details.
That’s all about Java 8 Lambda Expressions Examples.
In summary, lambda expressions in Java provide a more concise and expressive way to define behavior within code, making Java code more functional and enabling a more modular and elegant programming style.