Lambda Expression in Java

Lambda Expression in Java 
Lambda expression is a new feature. It was interduced in Java 8. Lambda expression is an anonymous function without name(anonymous function). It can’t extend abstract and concrete class. The Lambda expression is used to provide the implementation of an interface which has functional interface and it has only one abstract method That is called functional interface. It is very useful in Collections and Streams. It helps to iterate, filter and extract data from collection Streams. Lambda expression provides an annotation @FunctionalInterface, which is used to declare an interface as functional interface.

Types of Lambda Parameters:

1. Lambda with Zero Parameters
Syntax:
() -> System.out.println("Zero parameter lambda");

2. Lambda with a Single Parameter
Syntax:
(x) -> System.out.println("One parameter: " + x);

3. Lambda Expression with Multiple Parameters
Syntax:
(s1, s2) -> System.out.println("Multiple parameters: " + s1 + ", " + s2);

Why Use Lambda Expressions:

Concise and Readable Code: Significantly reduce boilerplate code.
Functional Programming: Treat functionality as a method argument (code as data).
Improved Readability: Code is easier to read and maintain.
Collections and Streams: Simplify operations like filtering, mapping, and iterating.
Event Handling: Defining event listeners concisely.
Seamless Stream API Integration: Lambdas work perfectly with the new Stream APIs.
Multithreading: Creating a new thread using the Runnable interface.

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

public class Demo{
    
    public static void main(String[] args){
        
        List<String> names = Arrays.asList(
            "Ali", "Boby", "Chari", "Aunty");

        System.out.println("All names:");
        names.forEach(name -> System.out.println(name));

        System.out.println("\nNames starting with 'A':");
        names.stream()
            .filter(n -> n.startsWith("A"))
            .map(n -> n.toUpperCase())
            .forEach(System.out::println);
    }
}


#Tags:  | Java | Java Keywords | Java Methods | Java Questions | Java FAQs | Java questions and answers |

*Disclaimer: We have published the above images and information for reference purpose only, for any changes on the content we refer to visit the Official Website to get the latest info.
NOTE: Free Career Hub Employees will not call any candidates towards Job Offer or Job assistance. We never charge any candidates for Jobs. Please be aware of fraudulent Calls or Emails.

Lambda Expression in Java

Post a Comment

0 Comments