Java lambda expressions are introduced in Java 8, which changes how we write Java code. By allowing us to create methods without names, called anonymous functions. This makes the code shorter and easier to read. Lambda expressions are especially useful for interfaces with only one method. They also reduce the need for long, anonymous classes. So, this Java lambda expression tutorial explains the basics of lambda expressions, their simple syntax, and the different types. It also shows how to create and use lambda functions, their benefits, and practical examples in Java programming.
Java lambda expressions allow you to create anonymous functions, which are methods without a name. They help make the code shorter and easier to read. By letting you pass methods as arguments or store them in variables. This is especially useful for interfaces with just one abstract method, called functional interfaces. The syntax is simple:
(parameters) -> expression |
or
(parameters) -> { statements; } |
Lambda expressions reduce the need for lengthy anonymous classes. It is also used with Java’s Stream API to process collections and handle parallel tasks more effectively.
Creating a Java lambda function involves writing a concise expression that implements a functional interface. Lambda expressions are a way to pass behavior as a parameter, making the code more flexible and readable. So, here is a step-by-step guide on how to create and use Java lambda expressions.
A functional interface is an interface with a single abstract method. Java provides several built-in functional interfaces in the java.util.function packages, such as Predicate, Function, Consumer, and Supplier.
Example of a functional interface:
@FunctionalInterface interface MyFunctionalInterface { void myMethod(); } |
A lambda method Java provides a clear and concise way to implement the abstract method of a functional interface.
Syntax:
(parameters) -> expression or (parameters) -> { statements; } |
Example with Runnable:
Runnable r = () -> System.out.println(“Hello, world!”); new Thread(r).start(); |
Example with ActionListener:
JButton button = new JButton(“Click me”); button.addActionListener(event -> System.out.println(“Button clicked”)); |
Example with Comparator:
List<String> list = Arrays.asList(“apple”, “orange”, “banana”); Collections.sort(list, (a, b) -> a.compareTo(b)); |
Define a Functional Interface
@FunctionalInterface interface MathOperation { int operate(int a, int b); } |
Implement the Functional Interface with Java lambda expressions
MathOperation addition = (a, b) -> a + b; MathOperation subtraction = (a, b) -> a – b; MathOperation multiplication = (a, b) -> a * b; MathOperation division = (a, b) -> a / b; |
Use the Lambda Expression
public class LambdaDemo { public static void main(String[] args) { MathOperation addition = (a, b) -> a + b; MathOperation subtraction = (a, b) -> a – b; MathOperation multiplication = (a, b) -> a * b; MathOperation division = (a, b) -> a / b;
System.out.println(“Addition: ” + operate(5, 3, addition)); System.out.println(“Subtraction: ” + operate(5, 3, subtraction)); System.out.println(“Multiplication: ” + operate(5, 3, multiplication)); System.out.println(“Division: ” + operate(6, 3, division)); }
private static int operate(int a, int b, MathOperation operation) { return operation.operate(a, b); } } |
A lambda method in Java refers to the method implemented using a lambda expression. It’s essentially a shorthand for implementing a functional interface’s abstract method. The implementation of a functional interface method using Java lambda expressions can be passed directly to methods expecting a functional interface type.
Example:
List<String> names = Arrays.asList(“John”, “Jane”, “Jack”, “Doe”);
// Using lambda expression to iterate over the list names.forEach(name -> System.out.println(name)); |
Here, we will explore the different types of Java Lambda Expressions, their benefits, and how to use them effectively.
A no-parameter lambda expression does not take any arguments. It is typically used when a task does not require any input parameters. The syntax is straightforward:
() -> System.out.println(“Hello, World!”); |
In this example, the lambda expression represents a block of code that prints “Hello, World!” to the console.
A single parameter lambda expression takes one argument. It simplifies the implementation of functional interfaces with a single method that takes one parameter.
(x) -> System.out.println(x); |
If the parameter type can be inferred, the parentheses can be omitted:
x -> System.out.println(x); |
Multiple-parameter Java lambda expressions take two or more arguments. This type is useful when the functional interface method requires more than one parameter.
(a, b) -> System.out.println(a + b); |
In this example, the lambda expression takes two parameters a and b, and prints their sum.
A lambda expression can also contain a return statement. This type is used when the functional interface method returns a value.
(a, b) -> { return a + b; }; |
If the lambda body contains only a single expression, the return keyword and braces can be omitted:
(a, b) -> a + b; |
When the lambda body contains multiple statements, they must be enclosed in braces {} and the return statement (if needed) must be explicitly stated.
(x, y) -> { int sum = x + y; int difference = x – y; return sum * difference; }; |
Lambda expressions can capture variables from their enclosing scope. These variables must be effectively final (i.e., not modified after initialization).
int factor = 2; (a) -> System.out.println(a * factor); |
In this example, the lambda expression captures the factor variable from its enclosing scope.
Lambda expressions offer several benefits in Java:
Let’s look at a practical example of how lambda expressions can be used in Java.
Example:
import java.util.*; import java.util.stream.*;
public class LambdaExample { public static void main(String[] args) { List<String> names = Arrays.asList(“Anna”, “Bob”, “Charlie”, “David”);
// Using lambda expression to filter and print names List<String> filteredNames = names.stream() .filter(name -> name.startsWith(“A”)) .collect(Collectors.toList());
filteredNames.forEach(name -> System.out.println(name)); } } |
In this example, the lambda expression name -> name.startsWith(“A”) is used to filter the list of names, retaining only those that start with “A”.
In conclusion, Java Lambda Expressions, introduced in Java 8, make writing Java code easier and more efficient. They allow you to write shorter clearer code by passing methods around like variables. This simplifies implementing interfaces with one method. Lambda expressions are beneficial with Java’s Stream API for processing collections. They come in types like no single and multiple parameters. Using them makes your code more readable and flexible. Embracing lambda expressions helps create more maintainable and scalable Java applications, making them essential for any Java developer.
Ans. Anonymous functions in Java are implemented using lambda expressions. For example, Runnable r = () -> System.out.println(“Running”); is an anonymous function.
Ans. Lambda functions offer a more concise and readable way to write code, especially for implementing functional interfaces. They also enable functional programming paradigms and enhance the capabilities of Java APIs.
About The Author:
The IoT Academy as a reputed ed-tech training institute is imparting online / Offline training in emerging technologies such as Data Science, Machine Learning, IoT, Deep Learning, and more. We believe in making revolutionary attempt in changing the course of making online education accessible and dynamic.
Digital Marketing Course
₹ 29,499/-Included 18% GST
Buy Course₹ 41,299/-Included 18% GST
Buy Course