Saturday, 3 February 2024

Lambda expressions examples and explanation through sample code

Through below code, I would like to explain Lambda expressions a new feature of java 8 and how it can be used efficiently to reduce the code.

Lambda expressions provides a concise way to express instances of single-method interfaces (functional interfaces).

A functional interface is an interface with exactly one abstract method, and it may contain multiple default or static methods.

Lambda expressions facilitate a more functional programming style in Java, allowing developers to pass behavior (code) as an argument to methods or to express instances of functional interfaces in a more compact form. The syntax of a lambda expression is concise and focused on expressing the behavior rather than the structure of the code.

Here's a brief overview of lambda expressions and their syntax:

(parameters) -> expression

or

(parameters) -> { statements; }



Parameters: A comma-separated list of parameters enclosed in parentheses. If there are no parameters, empty parentheses are used. For example:

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

·       () -> "Hello, World!"

Arrow (->): The arrow token, which separates the parameters from the body of the lambda expression.

Body: The body of the lambda expression, which can be a single expression or a block of statements. If the body is a single expression, you can omit the curly braces and the return keyword. If the body is a block of statements, you must use curly braces {} and include the return statement if needed.


Below is the sample example for the Lamda expressions


package com.examples;


import java.util.Arrays;

import java.util.List;

import java.util.stream.Collector;

import java.util.stream.Collectors;


public class LambdaExpressionsExample {

public static void main(String[] args) {

List<Integer> numbersList= Arrays.asList(1,2,3,4,5);

System.out.println("Initial Numbers");

numbersList.stream().forEach(n->System.out.print(n+" "));

System.out.println("\nSquare of the Numbers");

squareOfTheNumbers(numbersList).stream().forEach(n->System.out.print(n+" "));

System.out.println("\nSquare of even Numbers");

squareOfTheEvenNumbers(numbersList).stream().forEach(n->System.out.print(n+" "));

}

public static List<Integer> squareOfTheNumbers(List<Integer> numberList)

{

/*

* numberList: list containing integers (List<Integer>.

* @ .stream(): This method is called on numberList to convert it into a stream. 

* Streams in Java provide a sequence of elements on which you can perform various operations.

* @ .map(n -> n*n): The map operation transforms each element of the stream using the provided function.

*  In below case, it squares each element (n * n). The result is a new stream with the squared values.

*  

* @ collect(Collectors.toList()): Finally, the collect operation is used to gather the elements of the stream into a new list.

Collectors.toList() is a collector that collects the elements into a List.

*/

List<Integer>  result =numberList.stream().map(n -> n*n).collect(Collectors.toList());

return result;

}

public static List<Integer> squareOfTheEvenNumbers(List<Integer> numberList)

{

/*

* @ .filter(n -> n%2 == 0): The filter operation is used to retain only those elements that satisfy a given condition.

*    In this case, it keeps only the even numbers (where n % 2 == 0).

*/

numberList = numberList.stream().filter(n -> n%2==0).map(n-> n*n).collect(Collectors.toList());

return numberList;

}


}


Output - 

Initial Numbers
1 2 3 4 5 

Square of the Numbers
1 4 9 16 25 

Square of even Numbers
4 16 

No comments:

Post a Comment