0% found this document useful (0 votes)
4 views

Lambda Expression Fundamentals

The document explains the fundamentals of Lambda Expressions in Java, including their syntax, block expressions, and how they can be passed as arguments. It also discusses handling exceptions within lambda expressions, variable capture, and method references. These features enable more concise and functional-style programming in Java, particularly with collections and the Stream API.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lambda Expression Fundamentals

The document explains the fundamentals of Lambda Expressions in Java, including their syntax, block expressions, and how they can be passed as arguments. It also discusses handling exceptions within lambda expressions, variable capture, and method references. These features enable more concise and functional-style programming in Java, particularly with collections and the Stream API.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Lambda Expression Fundamentals, Block Lambda Expressions,Passing Lambda Expressions

as Arguments, Lambda Expressions and Exceptions, Variable Capture, Method References.

Lambda Expression Fundamentals in Java

A Lambda Expression in Java provides a clear and concise way to represent a function (or
block of code) that can be passed around and executed. It is primarily used to define the
behavior of methods in a functional style, which makes it easier to work with collections,
streams, and other functional programming paradigms.

Syntax of Lambda Expression

The basic syntax of a lambda expression is:

(parameters) -> expression

 Parameters: The list of parameters that the lambda expression accepts. It can be
empty, single, or multiple parameters.
 Arrow (->): The lambda operator that separates parameters from the body.
 Expression: A single expression or block of code that gets executed.

For example:

java
Code:

(int a, int b) -> a + b

1. Basic Lambda Expression Example

A simple lambda expression that adds two integers:

java
Code:

public class LambdaExample {


public static void main(String[] args) {
// A simple lambda expression
BinaryOperator<Integer> add = (a, b) -> a + b;

System.out.println("Sum: " + add.apply(10, 20)); //


Output: Sum: 30
}
}

Here, the lambda expression (a, b) -> a + b represents the addition operation, which
is passed to the BinaryOperator functional interface.
2. Block Lambda Expressions

In some cases, you may need a more complex block of code inside the lambda expression.
This is done by enclosing the code in curly braces {}.

Example:

Java Code:

public class LambdaBlockExample {


public static void main(String[] args) {
// Block lambda expression
TriFunction<Integer, Integer, Integer, Integer>
multiply = (a, b, c) -> {
int result = a * b * c;
System.out.println("Multiplication result: " +
result);
return result;
};

multiply.apply(2, 3, 4); // Output: Multiplication


result: 24
}
}

@FunctionalInterface
interface TriFunction<T, U, V, R> {
R apply(T t, U u, V v);
}

In this example, the block of code in the lambda expression multiplies the numbers and also
prints the result.

3. Passing Lambda Expressions as Arguments

Lambda expressions can be passed as arguments to methods, which is very useful in the
context of functional interfaces (e.g., Runnable, Comparator, etc.).

Example:

Java Code:

import java.util.Arrays;
import java.util.List;

public class LambdaAsArgumentExample {


public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana",
"cherry");

// Passing a lambda expression as an argument to a


method
printFilteredList(words, (word) -> word.length() > 5);
}

public static void printFilteredList(List<String> list,


Predicate<String> condition) {
for (String word : list) {
if (condition.test(word)) {
System.out.println(word);
}
}
}
}

In this example:

 We define a method printFilteredList that accepts a list and a Predicate


(a functional interface).
 We pass a lambda expression (word) -> word.length() > 5 to filter words
with more than 5 characters.

4. Lambda Expressions and Exceptions

Lambda expressions can throw exceptions, but it requires special handling because lambda
expressions are treated like anonymous methods, and throwing checked exceptions inside
them isn't allowed by default.

Example: Throwing an Exception in a Lambda Expression

To throw exceptions from lambda expressions, we need to wrap them in a try-catch block or
declare them in the functional interface signature.

java
Code:

import java.util.Arrays;
import java.util.List;

public class LambdaExceptionExample {


public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana",
"cherry");
// Passing a lambda expression that throws an
exception
words.forEach(word -> {
try {
if (word.length() > 5) {
throw new Exception("Word length is too
long: " + word);
}
System.out.println(word);
} catch (Exception e) {
System.out.println("Caught exception: " +
e.getMessage());
}
});
}
}

In this example, we throw an exception inside the lambda expression if the word's length is
greater than 5, and it is caught and handled.

5. Variable Capture

Lambda expressions in Java capture variables from the enclosing scope. This means that
lambda expressions can access variables defined in their enclosing method, but they can only
access final or effectively final variables.

Example:

Java Code:

public class LambdaVariableCaptureExample {


public static void main(String[] args) {
int multiplier = 2; // Local variable
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);

// Lambda expression that uses captured variable


'multiplier'
numbers.forEach(n -> System.out.println(n *
multiplier)); // Output: 2, 4, 6, 8
}
}

In this example, the multiplier variable is accessed inside the lambda expression.
Important: The variable multiplier must be either final or effectively final, meaning
its value cannot be changed after initialization.

6. Method References
Method references provide a shorthand for calling a method using a lambda expression. It
refers directly to a method using the :: operator.

There are four types of method references:

1. Reference to a static method.


2. Reference to an instance method.
3. Reference to a constructor.
4. Reference to an instance method of an arbitrary object.

6.1 Reference to a Static Method

java
Copy
public class MethodReferenceExample {
public static void main(String[] args) {
// Lambda expression to print each word
List<String> words = Arrays.asList("apple", "banana",
"cherry");
words.forEach(MethodReferenceExample::printWord);
}

// Static method
public static void printWord(String word) {
System.out.println(word);
}
}

In this example, we use a method reference MethodReferenceExample::printWord


instead of writing the lambda expression (word) ->
MethodReferenceExample.printWord(word).

6.2 Reference to an Instance Method

java
Copy
public class MethodReferenceExample {
public static void main(String[] args) {
MethodReferenceExample example = new
MethodReferenceExample();
List<String> words = Arrays.asList("apple", "banana",
"cherry");

// Using instance method reference


words.forEach(example::printWord);
}

// Instance method
public void printWord(String word) {
System.out.println(word);
}
}

Here, example::printWord is a method reference to the instance method printWord.

6.3 Reference to a Constructor

java
Copy
import java.util.*;

public class ConstructorReferenceExample {


public static void main(String[] args) {
// Using a constructor reference to create a new
Product object
List<Product> products = Arrays.asList(
new Product(1, "Laptop", 50000, "Electronics",
4.5),
new Product(2, "Smartphone", 15000,
"Electronics", 4.2)
);

// Creating a list using constructor reference


List<Product> productList = Arrays.asList(
new Product(3, "Headphones", 5000,
"Accessories", 3.8),
new Product(4, "Smartwatch", 20000,
"Electronics", 4.8)
);

// Print products using constructor method reference


productList.forEach(System.out::println);
}
}

In this example, the Product::new reference can be used if we are creating new
Product objects via a constructor.

Summary

 Lambda Expressions simplify writing code by providing a concise way to represent


functions as parameters or objects.
 Block Lambdas allow more complex functionality within the lambda body.
 Passing Lambda Expressions as arguments allows functional programming patterns
like filtering, sorting, and mapping.
 Exceptions in Lambdas require special handling since lambdas cannot directly throw
checked exceptions unless handled.
 Variable Capture allows lambda expressions to access local variables but requires
them to be effectively final.
 Method References provide a shorthand to invoke methods directly in place of
lambda expressions.

By using these features of Java, you can write more concise, functional-style code and take
advantage of the powerful capabilities of the Stream API, functional interfaces, and other
Java libraries.

You might also like