Categories: Java

Java Lambda Expressions Explained with Examples

The article represents different viewpoints on Java Lambda Expressions (Java 8) to help Java developers understand what, why, when, how of Lambda expressions.

  • Lambda expressions are nothing but a way to abstract behavior unlike the object-oriented programming which is based upon the abstraction of data in form of object. Lambda expressions are used to assign the behavior to a variable or pass the behavior in between method calls instead of wrapping the behavior in an object and working with the objects. Take a look at the following example to understand the Lambda expressions better.Remember, the famous addActionListener method on button to capture the button-click event and, take action when the button is clicked such as that illustrated (System.out.println) in following example.

    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
    System.out.println("button clicked");
    }
    });

    Lets try and understand what’s happening in above code. In above example, we are creating a new object which provides an implementation of the ActionListener class. As per the requirement, all that is needed is to manifest the behavior such as print “button clicked” when the button click event occurs. To achieve this objective, there is created an anonymous inner class and method actionPerformed is implemented in form of printing “button clicked”. To quickly recall, anonymous inner class is used to pass the code as data. Would you agree with following observations for above piece of code?
    • Unnecessary piece of code: Does not that seem unnecessary piece of code (boilerplate) when there is just the need of only printing the statement “button clicked”?
    • Why Create Object when all that is needed is to manifest a behavior?: Does not that look like a limitation posed by Java to create an object in order to manifest the behavior of printing “button clicked”?

    The above can be avoided by use of what is termed as Lambda Expressions. Lambda expression can be used to easily associate behavior of printing “button clicked” without having need of boilerplate code in following manner:

    ActionListener actionListener = event -> {
    System.out.println( “button clicked” )
    };
    button.addActionListener( actionListener );

    Note that boilerplate code is no more needed. The code also becomes easy to read and understand. The above code represents that the fact that one argument “event” is passed to the code inside the braces.

    Lambda Expression with No Arguments

    This is used to implement Runnable interface which has got just one method such as run() that takes no argument and return void type.

    Runnable runnable = () -> System.out.println(“Hello World”);

    OR,

    Runnable runnable = () -> {
    System.out.print(“Hello”);
    System.out.println(” World”);
    };


    Lambda Expression with Multiple Arguments

    Below represents examples when there are multiple arguments for methods and which need to be represented as Lambda expression:

    BinaryOperator<Long> add = (x, y) -> x + y;
    BinaryOperator<Long> addExplicit = (Long x, Long y) -> x + y;

    Above represents Lambda expression assigned to “add” variable which is equivalent to method with two argument x, and y and statement that adds up x and y. Note that “add” variable does not store the value of addition of x and y. However, it represents the code that adds up the variable.

  • Following are different types of Lambda expressions
    • Functional Interfaces: A functional interface is an interface with a single abstract method that is used as the type of a lambda expression. From above example, it could be inferred that ActionListener could be called as functional interface as it has got just one method, actionPerformed.
    • Type Inference: The type inference used in lambdas is actually an extension of the target type inference introduced in Java 7.

[adsenseyu1]

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

Recent Posts

Agentic Reasoning Design Patterns in AI: Examples

In recent years, artificial intelligence (AI) has evolved to include more sophisticated and capable agents,…

2 months ago

LLMs for Adaptive Learning & Personalized Education

Adaptive learning helps in tailoring learning experiences to fit the unique needs of each student.…

3 months ago

Sparse Mixture of Experts (MoE) Models: Examples

With the increasing demand for more powerful machine learning (ML) systems that can handle diverse…

3 months ago

Anxiety Disorder Detection & Machine Learning Techniques

Anxiety is a common mental health condition that affects millions of people around the world.…

3 months ago

Confounder Features & Machine Learning Models: Examples

In machine learning, confounder features or variables can significantly affect the accuracy and validity of…

3 months ago

Credit Card Fraud Detection & Machine Learning

Last updated: 26 Sept, 2024 Credit card fraud detection is a major concern for credit…

3 months ago