DEV Community

Akshay Dev
Akshay Dev

Posted on

Lambda Expressions In Java

In Java, a Lambda expression is like a shortcut for creating a small piece of code that does something specific. It's especially useful when you only need a quick function and don't want to write a whole method.

Imagine you have something called a "functional interface," which is just a special kind of interface in Java that has only one job to do. We call it "functional" because it's designed to perform a specific function.

Now, instead of writing a regular method and going through the whole process, Java 8 introduced Lambda expressions to make things quicker. It's a way to write a brief piece of code that takes some input, does something with it, and gives you a result.

  • (String name) -> { return "Hi"+name } Lambda Expression

  • This function takes one input parameter does some operations with it and returns the result.

A Sample Code With Explanation

  • It is an interface which has an abstract method to find the area of a rectangle.

public interface Rectangle {
void areaOfARectangle(int length, int width);
}

  • Main Function
    public class LambdaExpressionExamples {

    public static void main(String arg[]) {
    //Without Using Lambda

    Rectangle rectangle = new Rectangle() {
        @Override
        public void areaOfARectangle(int length, int width) {
            System.out.print("Area Of A Rectangle: "+length * 
                             width);
        }
    };
    
    rectangle.areaOfARectangle(5, 10);
    
    //With Lambda
    
    Rectangle rectangle1 = (int length, int width) -> {
        System.out.print("Area Of An Rectangle: "+length * 
                         width);
    };
    
    rectangle1.areaOfARectangle(10, 4);
    

    }
    }

Top comments (0)