Lambda Expressions: One of the most significant additions in Java 8 is the support for lambda expressions. Lambda expressions provide a concise way to represent anonymous functions and enable functional programming in Java.

A lambda expression is a concise way to represent a functional interface, which is an interface with a single abstract method. It allows you to express instances of these functional interfaces more compactly and readably.

What is Functional Interface?
Java 1.8 feature?

The syntax for a lambda expression in Java is as follows:

r
(parameters) -> expression

or

rust
(parameters) -> { statements; }

Let's break down the parts of a lambda expression:

  1. Parameters: The parameters are optional but if present, they specify the input arguments for the lambda expression. If there is only one parameter, you can omit the parentheses. For example, (x, y), x, or ().

  2. Arrow token: The arrow token -> separates the parameters from the body of the lambda expression.

  3. Expression or statement block: The body of the lambda expression can be either a single expression or a block of statements enclosed in braces. If the body is a single expression, it is implicitly returned. If it is a block of statements, you need to use the return keyword explicitly if you want to return a value.

Here's an example of a lambda expression that takes two integers and returns their sum:

java
// Lambda expression
MathOperation addition = (a, b) -> a + b; 
// Usage 
int result = addition.operation(35); 
// result = 8

In the example above, MathOperation is a functional interface with a single abstract method called operation(). The lambda expression (a, b) -> a + b represents an implementation of that method, where it adds the two integers a and b.

Lambda expressions are commonly used with functional interfaces to write more concise and expressive code, especially when working with collections, threads, and event-driven programming. They enable you to write inline, anonymous functions and improve the readability and maintainability of your code.

Lambda Expression Example With ArrayList:


java
import java.util.ArrayList;
 import java.util.List; 
public class LambdaExample { 
public static void main(String[] args) {
 List<String> fruits = new ArrayList<>();
 fruits.add("Apple"); 
fruits.add("Banana"); 
fruits.add("Orange"); 
fruits.add("Mango");
 // Using lambda expression to iterate and print each element of the list 
fruits.forEach(fruit -> System.out.println(fruit)); 
// Using lambda expression to filter the list based on a condition 
fruits.removeIf(fruit -> fruit.startsWith("B"));
 System.out.println("Filtered List:"); 
fruits.forEach(fruit -> System.out.println(fruit));
 } 
}

In this example, we have a list of fruits, and we use lambda expressions to perform two operations:

  1. Iterating and printing each element of the list:

    • The forEach() method is used to iterate over each element of the list.
    • The lambda expression fruit -> System.out.println(fruit) represents an implementation of the Consumer functional interface, where fruit is the input parameter, and System.out.println(fruit) is the body of the method.
  2. Filtering the list based on a condition:

    • The removeIf() method is used to remove elements from the list that match a given condition.
    • The lambda expression fruit -> fruit.startsWith("B") represents an implementation of the Predicate functional interface, where fruit is the input parameter, and fruit.startsWith("B") is the condition to be checked.

When you run this code, it will iterate over the list and print each fruit. Then it will remove any fruits that start with the letter "B" and print the filtered list.


Here's an example that demonstrates the use of a lambda expression(With two-parameter) with a functional interface in Java:

java
@FunctionalInterface 
interface MathOperation { 
int operation(int a, int b); } 
public class LambdaExample { 
public static void main(String[] args) { 
// Lambda expression to perform addition 
MathOperation addition = (a, b) -> a + b; 
// Lambda expression to perform subtraction 
MathOperation subtraction = (a, b) -> a - b; 
// Lambda expression to perform multiplication 
MathOperation multiplication = (a, b) -> a * b; 
// Usage of lambda expressions 
int result1 = addition.operation(53); // result1 = 8 
int result2 = subtraction.operation(104); // result2 = 6 
int result3 = multiplication.operation(62); // result3 = 12 
System.out.println("Addition: " + result1);
 System.out.println("Subtraction: " + result2); System.out.println("Multiplication: " + result3);
 }
 }

In this example, we define a functional interface called MathOperation with a single abstract method called operation(), which takes two integers as parameters and returns an integer.

We then use lambda expressions to provide implementations of this functional interface for different mathematical operations:

  • The lambda expression (a, b) -> a + b represents the addition operation.
  • The lambda expression (a, b) -> a - b represents the subtraction operation.
  • The lambda expression (a, b) -> a * b represents the multiplication operation.

In the main() method, we create instances of the functional interface using the lambda expressions, and then we use those instances to perform the respective operations.

When you run this code, it will perform addition, subtraction, and multiplication using the lambda expressions and print the results.


Here's an example that demonstrates the use of a lambda expression without parameters in Java:

java
@FunctionalInterface interface Greeting
void sayHello()
public class LambdaExample {
public static void main(String[] args)
// Lambda expression without parameters to greet in English
Greeting englishGreeting = () -> System.out.println("Hello!"); 
// Lambda expression without parameters to greet in French 
Greeting frenchGreeting = () -> System.out.println("Bonjour!"); 
// Usage of lambda expressions
englishGreeting.sayHello(); // Prints "Hello!" 
 frenchGreeting.sayHello(); // Prints "Bonjour!" 
 }
 }

In this example, we define a functional interface called Greeting with a single abstract method called sayHello() that doesn't take any parameters and returns void.

We then use lambda expressions to provide implementations of this functional interface for different greetings:

  • The lambda expression () -> System.out.println("Hello!") represents the English greeting.
  • The lambda expression () -> System.out.println("Bonjour!") represents the French greeting.

In the main() method, we create instances of the functional interface using the lambda expressions, and then we use those instances to invoke the sayHello() method.

When you run this code, it will use the lambda expressions without any parameters to greet in English and French, respectively, and print the corresponding greetings.


Here's an example that demonstrates the use of a lambda expression with one parameter in Java:

java
@FunctionalInterface 
interface StringLength
int getLength(String str);
 } 
public class LambdaExample
public static void main(String[] args)
// Lambda expression with one parameter to get the length of a string 
StringLength stringLength = str -> str.length(); 
// Usage of lambda expression 
String input = "Hello, Lambda!"
int length = stringLength.getLength(input); 
 System.out.println("Length of the string: " + length); 
 } 
}

In this example, we define a functional interface called StringLength with a single abstract method called getLength() that takes a String parameter and returns an int.

We then use a lambda expression with one parameter to provide an implementation of this functional interface:

  • The lambda expression str -> str.length() represents a function that takes a String parameter str and returns its length using the length() method.

In the main() method, we create an instance of the functional interface using the lambda expression, and then we use that instance to invoke the getLength() method and calculate the length of a string.

When you run this code, it will use the lambda expression with a single parameter to calculate and print the length of the input string "Hello, Lambda!".