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. For latest updates and blogs, follow us on Twitter. 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. Check out my other blog, Revive-n-Thrive.com

Recent Posts

Pricing Analytics in Banking: Strategies, Examples

Last updated: 15th May, 2024 Have you ever wondered how your bank decides what to…

16 hours ago

How to Learn Effectively: A Holistic Approach

In this fast-changing world, the ability to learn effectively is more valuable than ever. Whether…

3 days ago

How to Choose Right Statistical Tests: Examples

Last updated: 13th May, 2024 Whether you are a researcher, data analyst, or data scientist,…

3 days ago

Data Lakehouses Fundamentals & Examples

Last updated: 12th May, 2024 Data lakehouses are a relatively new concept in the data…

4 days ago

Machine Learning Lifecycle: Data to Deployment Example

Last updated: 12th May 2024 In this blog, we get an overview of the machine…

4 days ago

Autoencoder vs Variational Autoencoder (VAE): Differences, Example

Last updated: 12th May, 2024 In the world of generative AI models, autoencoders (AE) and…

4 days ago