Pages

Lambda Expressions


Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression. It is very useful in collection library. It helps to iterate, filter and extract data from collection.

The Lambda expression is used to provide the implementation of an interface which has functional interface. It saves a lot of code. In case of lambda expression, we don't need to define the method again for providing the implementation. Here, we just write the implementation code. Java lambda expression is treated as a function, so compiler does not create .class file.

Functional Interface :

Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface. Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.


What is Lambda Expression?

Lambda Expression is treated as a function, so compiler does not create dot class file.


Why use Lambda Expression?

Lambda Expression to provide the implementation of Functional interface and Less Coding.


Java without Lambda Expression Example

package com.jaladhi;
public interface Drawable {
      public void draw();
}
public class ZeroExample {
      public static void main(String[] args) {
            int width = 10;
            Drawable drawable = new Drawable() {
                  @Override
                  public void draw() {
                        System.out.println("Drawing : " + width);
                  }
            };
            drawable.draw();
      }
}

Output :

Drawing : 10

Java Lambda Expression Example (No Parameters)

package com.jaladhi;
public interface Readable {
      public void read ();
}
public class LambdaRead {
      public static void main(String [ ] args) {
            Readable r = ( ) -> {
                  System.out.println(“Reading the Java Books”);
            };
            r.read();
      }
}

Output :

Reading the Java Books.

Java Lambda Expression Example (No Parameters)

package com.jaladhi;
@FunctionalInterface
public interface Drawable {
      public void draw();
}
public class FirstExample {
      public static void main(String[] args) {
            int width = 10;
            Drawable drawable = () -> {
                  System.out.println("Drawing : " + width);
            };
            drawable.draw();
      }
}

Output :

Drawing : 10

Java Lambda Expression Example (Single Parameters)

package com.jaladhi;
public interface Sayable {
      public String say(String name);
}
public class SecondExample {
      public static void main(String[] args) {
            // Lambda expression with single parameter.
            Sayable say1 = (name) -> {
                  return "Lambda Expression " + name;
            };
            System.out.println(say1.say("with Parentheses"));
            // You can omit function parentheses.
            Sayable say2 = name -> {
                  return "Lambda Expression " + name;
            };
            System.out.println(say2.say("without Parentheses"));
      }
}

Output :

Lambda Expression with Parentheses
Lambda Expression without Parentheses

Java Lambda Expression Example (Multiple Parameters)

package com.jaladhi;
public interface Addable {
      public int add(int a,int b);
}
public class Addition {
      public static void main(String[] args) {
            // Multiple Parameters in Lambda Expression
            Addable ad1=(a,b)->(a+b);
            System.out.println("Multiple Parameters : " + ad1.add(10,20));
            // Multiple Parameters with Data Type in Lambda Expression
            Addable ad2=(int a,int b)->(a+b);
            System.out.println("Multiple Parameters with Data Type : " + ad2.add(100,200));
      }
}

Output :

Multiple Parameters : 30
Multiple Parameters with Data Type : 300

Java Lambda Expression Example (With or Without Return Keyword)

package com.jaladhi;
public interface Subbtrable {
      public int subtract(int a, int b);
}
public class Subtraction {
      public static void main(String[] args) {
            // Lambda Expression without return keyword.
            Subbtrable sub = (a,b)->(a-b);
            System.out.println("Without Return Keyword : " + sub.subtract(50, 20));
            // Lambda Expression with return keyword.
            Subbtrable subtract = (int a, int b) -> {
                  return (a-b);
            };
            System.out.println("With Return Keyword : " + subtract.subtract(150, 60));
      }
}

Output :

Without Return Keyword : 30
With Return Keyword : 90

Java Lambda Expression Example (For Each Loop)

package com.jaladhi;
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
      public static void main(String[] args) {
            List list = new ArrayList();
            list.add("Ankit");
            list.add("Mayank");
            list.add("Irfan");
            list.add("Jai");
            list.forEach((n) -> System.out.println(n));
      }
}

Output :

Ankit
Mayank
Irfan
Jai

Java Lambda Expression Example (Multiple Statements)

package com.jaladhi;
public interface Readable {
      public String read(String message);
}
public class SixExample {
      public static void main(String[] args) {
            // You can pass multiple statements in Lambda Expression
            Readable read = (message) -> {
                  String str1 = "I would like to say, ";
                  String str2 = str1 + message;
                  return str2;
            };
            System.out.println(read.read("Time is Precious."));
      }
}

Output :

I would like to say, Time is Precious.

Java Lambda Expression Example (Creating Thread)

package com.jaladhi;
public class ThreadExample {
      public static void main(String[] args) {
            //Thread Example without Lambda
            Runnable runnable1 = new Runnable() {
                  @Override
                  public void run() {
                        System.out.println("First Thread is running ....");
                  }
            };
            Thread first = new Thread(runnable1);
            first.start();
            //Thread Example with Lambda
            Runnable runnable2 = () -> {
                  System.out.println("Second Thread is running ....");
            };
            Thread second = new Thread(runnable2);
            second.start();
      }
}

Output :

First Thread is running ....
Second Thread is running ....

Java Lambda Expression Example (Comparator)

package com.jaladhi;
public class Product {
      public int id;
      public String name;
      public float price;
      public Product(int id, String name, float price) {
            super();
            this.id = id;
            this.name = name;
            this.price = price;
      }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ProductController {
      public static void main(String[] args) {
            List list=new ArrayList();
            list.add(new Product(1,"HP Laptop",25000f));
            list.add(new Product(3,"Keyboard",300f));
            list.add(new Product(2,"Dell Mouse",150f));
            System.out.println("Sorting on the basis of Name...");
            // Implementing Lambda Expression
            Collections.sort(list, (p1,p2)-> {
                  return p1.name.compareTo(p2.name);
            });
            for(Product p : list) {
                  System.out.println("ID : " + p.id);
                  System.out.println("Name : " + p.name);
                  System.out.println("Price : " + p.price);
            }
      }
}

Output :

Sorting on the basis of Name...
ID : 2
Name : Dell Mouse
Price : 150.0
ID : 1
Name : HP Laptop
Price : 25000.0
ID : 3
Name : Keyboard
Price : 300.0

Java Lambda Expression Example (Filter Collection Data)

package com.jaladhi;
public class Product {
      public int id;
      public String name;
      public float price;
      public Product(int id, String name, float price) {
            super();
            this.id = id;
            this.name = name;
            this.price = price;
      }
}
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class FilterExample {
      public static void main(String[] args) {
            List list=new ArrayList();
            list.add(new Product(1,"Samsung A5",17000f));
            list.add(new Product(3,"Iphone 6S",65000f));
            list.add(new Product(2,"Sony Xperia",25000f));
            list.add(new Product(4,"Nokia Lumia",15000f));
            list.add(new Product(5,"Redmi4 ",26000f));
            list.add(new Product(6,"Lenevo Vibe",19000f));
            // using lambda to filter data
            Stream filtered_data = list.stream().filter(p -> p.price > 20000);
            // using lambda to iterate through collection
            filtered_data.forEach(
                  product -> System.out.println(product.name + " : " + product.price);
            );
      }
}

Output :

Iphone 6S : 65000.0
Sony Xperia : 25000.0
Redmi4 : 26000.0