Loading Posts...

Java Lambda Expressions Example | Lambda Expression in Java

Java Lambda Expressions Example | Lambda Example in Java

Java Lambda Expressions Example | Lambda Expression in Java is today’s topic. The lambda expressions in java are unnamed methods, which are used to implement the abstract method of functional interface. Lambda expressions are also known as closures. They are used to call methods as objects.

The lambda expressions are added in Java 8 and provide below functionalities.

  1. It enables to treat functionality as the method argument, or code as data.
  2. The function that can be created without belonging to any class.
  3. The lambda expression can be passed around as if it was an object and executed on demand.

Java Lambda Expressions

Lambda expressions use the lambda operator (->) which divides the lambda expression into two parts. The part on the left side contains the parameters required by the lambda expression, and the part on the right side specifies the body of the lambda expression. The parameters are enclosed in parenthesis, and the body is enclosed in curly braces.

Note: A functional interface is an interface which contains only one abstract method. A functional interface is also known as SAM(Single Abstract Method) interface. @FunctionalInterface could be written to create a functional interface which will show an error if the properties of the functional interface got violated. If an interface declares an abstract method which overrides any method of the Object class, then it will not be considered as the ‘only abstract’ method of the functional interface, That is, we need to write another abstract method to make a functional interface. 

Syntax of the lambda expression: See the following picture.

 

Java Lambda Expressions Example

#Why use Lambda Expression

  1. It provides the implementation of a functional interface.
  2. Less coding.

#Important points:

  • If the lambda expression has only one parameter, it is not required to enclose the parameter in the parenthesis on the left side.

    • (int a) -> {System.out.println(a);} // This is valid
    • int a -> {System.out.println(a);}    // This is also valid and the first expression can be written like this one 
  • You can provide as many parameters as you want in the lambda expression (including zero).

    • zero parameters: ()->{System.out.println(“hello”);}
    • one parameter: (int a)->{System.out.println(a);}
    • multiple parameters: (int a, int b, int c)->{System.out.println(a+b+c);}
  • The parameter types can also be dropped if all the parameters are of same type.

    • (int a, int b, int c)->{System.out.println(a+b+c);}
    • //the above expression can be written as: (a, b, c)->{System.out.println(a+b+c);}
  • Body of the lambda expression can contain either a single statement or a block of code containing multiple expressions.

    • single statement:               (int a, int b, int c)->{System.out.println(a+b+c);}
    • block of code:                       (int a, int b, int c)->{int z=a+b+c; System.out.println(“z is: ”+z);} 
  • When there is single statement in the body, the lambda expression is called Expression lambda or Expression body. When the body contains a block of code, it is called Block body or Block lambda.
  • When there is a single statement in the body of the lambda expression, which is also a return statement, then the return keyword is optional.
  • The curly braces in the body of the Expression body are also optional.

    • (int a, int b)->{return a+b;}
    • //above statement can be written as (int a, int b)-> a+b;

#Programs

See the following Program to show the working of a lambda expression with a single parameter.

//Functional Interface
interface Circle {
  // Abstract method
  public double circumference(double radius);
}

class Example1 {
  public static void main(String[] args) {
    // writting lambda expression for functional interface Circle
    Circle c = radius -> 2 * 3.14 * radius;
    // this statement is equivalent to
    // Circle c = (double radius) -> { return 2*3.14*radius; };

    double circum = c.circumference(12);
    System.out.println("circumference is: " + circum);
  }
}

See the following output.

 

Java Lambda Expressions

Example2.java: Program to show the working of the lambda expression with multiple parameters. Also, confirm with the help of an example that when could we drop the parameter types. See the following program.

interface Sample {
  public void greater(int a, int b);
}

interface Message {
  public void show(String name, int age);
}

class Example2 {
  public static void main(String[] args) {
    // parameter types are dropped as they are of same type
    Sample s = (a, b) -> {
      if (a > b)
        System.out.println(a + " is greater");
      else if (b > a)
        System.out.println(b + " is greater");
      else
        System.out.println("both are equal");
    };
    s.greater(10, 15);

    Message m = (String name, int age) -> {
      System.out.println(name + " is " + age + " years old");
    };
    // parameter types are specified because they are of different types
    m.show("max", 18);
  }
}

See the following output.

 

Lambda Example in Java

Example3.java: Program to show the working of lambda expression without any parameters.

interface Message {
  public void showMessage();
}

class Example3 {
  public static void main(String[] args) {
    // lambda expressions with no parameters
    Message m1 = () -> {
      System.out.println("Good Morning everyone!");
    };
    Message m2 = () -> {
      System.out.println("Good Afternoon everyone!");
    };
    Message m3 = () -> {
      System.out.println("Good Night everyone!");
    };

    m1.showMessage();
    m2.showMessage();
    m3.showMessage();
  }
}

See the below output.

Java Lambda Expressions Tutorial

 

#Filter Collection Data using Lambda Function

In this example, we will take Java ArrayList to create the collection of data. See the following code.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

class Product {
  int id;
  String name;
  float price;

  public Product(int id, String name, float price) {
    super();
    this.id = id;
    this.name = name;
    this.price = price;
  }
}

public class Conditionals {
  public static void main(String[] args) {
    List list = new ArrayList();
    list.add(new Product(1, "Samsung A5", 17000f));
    list.add(new Product(3, "iPhone 10XS", 65000f));
    list.add(new Product(2, "MI A1", 14000f));
    list.add(new Product(4, "Huwaei", 15000f));
    list.add(new Product(5, "Redmi4 ", 26000f));
    list.add(new Product(6, "Lenevo K3 Note", 14000f));

    // using lambda to filter data
    Stream filtered_data = list.stream().filter(p -> p.price > 19000);

    // using lambda to iterate through collection
    filtered_data.forEach(product -> System.out.println(product.name + ": " + product.price));
  }
}

See the following output.

➜  java javac Conditionals.java
➜  java java Conditionals
iPhone 10XS: 65000.0
Redmi4 : 26000.0
➜  java

#Java Comparator using Lambda Expressions

In the below code, we will use the Java Comparator.

We will sort the values of the ArrayList. See the following code example.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Product {
  int id;
  String name;
  float price;

  public Product(int id, String name, float price) {
    super();
    this.id = id;
    this.name = name;
    this.price = price;
  }
}

public class Conditionals {
  public static void main(String[] args) {
    List list = new ArrayList();

    // Adding Products
    list.add(new Product(1, "Mobile", 25000f));
    list.add(new Product(3, "Laptop", 300f));
    list.add(new Product(2, "Sony Playstation", 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(p.id + " " + p.name + " " + p.price);
    }

  }
}

See the following output.

➜  java javac Conditionals.java
➜  java java Conditionals
Sorting on the basis of name...
3 Laptop 300.0
1 Mobile 25000.0
2 Sony Playstation 150.0
➜  java

#Creating Thread using Java Thread

You can use a lambda expression to run thread. In the following example, we are implementing the run method by using a lambda expression.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Conditionals {
  public static void main(String args[]) {
    Runnable r1 = new Runnable() {
      public void run() {
        System.out.println("First is running...");
      }
    };
    Thread t1 = new Thread(r1);
    t1.start();
    // Thread Example with lambda
    Runnable r2 = () -> {
      System.out.println("Second is running...");
    };
    Thread t2 = new Thread(r2);
    t2.start();
  }
}

See the following output.

➜  java javac Conditionals.java
➜  java java Conditionals
First is running...
Second is running...
➜  java

#Lambda Expression Multiple Statements

See the following example of multiple statements.

@FunctionalInterface
interface Sayable {
  String say(String message);
}

public class Conditionals {
  public static void main(String[] args) {

    // You can pass multiple statements in lambda expression
    Sayable person = (message) -> {
      String str1 = "Is this true not to say sorry, ";
      String str2 = str1 + message;
      return str2;
    };
    System.out.println(person.say("time is precious."));
  }
}

See the following output.

➜  java javac Conditionals.java
➜  java java Conditionals
Is is true not to say sorry, time is precious.
➜  java

Finally, Java Lambda Expressions Example | Lambda Example in Java is over.

The post Java Lambda Expressions Example | Lambda Expression in Java appeared first on AppDividend.

Get Free Email Updates!

Signup now and receive an email once I publish new content.

I agree to have my personal information transfered to MailChimp ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.

user

The author didnt add any Information to his profile yet

Loading Posts...