Tuesday, 10 October 2017

Java 8 | Usage of Java 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 (Function interface).
It helps to iterate, filter (using streams) and extracts data from the collection. Before lambda expression, the anonymous inner class was the only option to implement the method.

Syntax
A lambda in Java essentially consists of three parts: a parenthesized set of parameters, an arrow, and then a body, which can either be a single expression or a block of Java code.
(Set of parameters) -> {body}

Set of parameters: It can be empty or non-empty as well.
Arrow-token: It is used to link arguments-list and body of expression.
Body: Contains expressions and statements for lambda expression.

Java Example without Lambda Expression
package com.java8;
interface Addition {
     public void add(int a, int b);
}

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

           /** Without lambda, Addition implementation using anonymous class .*/
           Addition d = new Addition() {
                public void add(int a, int b) {
                     System.out.println("Sum is" + (a + b));
                }
           };
           d.add(3, 5);
     }
}

Output: Sum is 8

Java Example with Lambda Expression
package com.java8;
interface Addition {
     public void add(int a, int b);
}

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

           /** Addition implementation using lambda expression.*/
           Addition d = (int a, int b)-> {
                System.out.println("Lambda | Sum is "+(a+b));
           };
           d.add(3, 5);
     }
}
Output: Lambda | Sum is 8

Few examples of Lambda expression
package com.java8;
interface Hello {
     public String sayHello();
}

public class HelloLambda {
     public static void main(String[] args) {
           Hello hello = () -> {
                return "Hello! I am Lambda without parameter.";
           };
           System.out.println(hello.sayHello());
     }
}
Output: Hello! I am Lambda without parameter.

Java Lambda Expression with Single Parameter
package com.java8;
interface Hello {
     public String sayHello(String name);
}

public class HelloLambda {
     public static void main(String[] args) {
           Hello hello = (String name) -> {
                return "Hello "+name +"! I am Lambda with Single parameter.";
           };
           System.out.println(hello.sayHello("Coder"));
     }
}
Output: Hello Coder! I am Lambda with Single parameter.

Java Lambda Expression with Multiple Parameters
package com.java8;
interface Addition {
     public void add(int a, int b);
}

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

           /** Without lambda, Addition implementation using anonymous class .*/
           Addition d = new Addition() {
                public void add(int a, int b) {
                     System.out.println("Sum is" + (a + b));
                }
           };
           d.add(3, 5);
     }
}

Output: Sum is 8

Java Lambda Expression with or without return keyword
If there is only one statement, you may or may not use return keyword. You must use return keyword when lambda expression contains multiple statements.
package com.java8;
interface Addition {
     public int add(int a, int b);
}

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

           /** Multiple statement required the return type. */
           Addition mulAdd = (int a, int b) -> {
                return (a + b);
           };

           System.out.println("Multiple statement: Sum is " + mulAdd.add(3, 5));
          
           /** Single statement, return type not required. */
           Addition singAdd = (int a, int b) ->  (a + b);

           System.out.println("Single statement: Sum is " + singAdd.add(3, 5));
     }
}
Output:
Multiple statement: Sum is 8
Single statement: Sum is 8

Foreach Loop using Java Lambda expression
package com.java8;
import java.util.ArrayList;
import java.util.List;

public class LambdaForEach {

     public static void main(String[] args) {

           List<String> list = new ArrayList<String>();
           list.add("Algos");
           list.add("Paras");
           list.add("Sattu");

           /* For each for Lambda expression. */
           list.forEach((n) -> System.out.println(n));
     }
}
Output:
Algos
Paras
Sattu


Create Thread using Lambda expression
package com.java8;
public class LambdaThread {
     public static void main(String[] args) {
          
           /** Thread Example without lambda. */
           Runnable r1 = new Runnable() {
                public void run() {
                     System.out.println("Thread1 is running...");
                }
           };
           Thread t1 = new Thread(r1);
           t1.start();
          
           /** Thread Example with lambda .*/
           Runnable r2 = () -> {
                System.out.println("Thread2 is running...");
           };
           Thread t2 = new Thread(r2);
           t2.start();
     }
}
Output:
Thread1 is running...
Thread2 is running...



As per the definition of Java lambda expression, it can be used in the collection framework. It provides the efficient and concise way to iterate, filter and fetch data. Check the below implementation for the same:


Lambda to implement the Comparator

package com.java8;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Employee {
     int empId;
     String name;

     public Employee(int empId, String name) {
           this.empId = empId;
           this.name = name;
     }
}

public class LambdaComparator {
    
     public static void main(String[] args) {
          
           List<Employee> employees = new ArrayList<Employee>();

           /** Adding Products. */
           employees.add(new Employee(1, "Algos"));
           employees.add(new Employee(3, "Paras"));
           employees.add(new Employee(2, "Deshraj"));

           System.out.println("Sorting on the basis of Employee Name...");

           /** Implementing lambda expression .*/
           Collections.sort(employees, (p1, p2) -> {
                return p1.name.compareTo(p2.name);
           });
          
           for (Employee p : employees) {
                System.out.println(p.empId + " " + p.name);
           }
     }
}
Output:
Sorting on the basis of Employee Name...
1 Algos
2 Deshraj
3 Paras

Filter Collection Data using Streams & Lambda

package com.java8;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

class Employee {
     int empId;
     String name;
     long salary;

     public Employee(int empId, String name, long salary) {
           this.empId = empId;
           this.name = name;
           this.salary = salary;
     }
}

public class LambdaComparator {
    
     public static void main(String[] args) {
          
           List<Employee> employees = new ArrayList<Employee>();

           /** Adding Employees. */
           employees.add(new Employee(1, "Algos", 130000L));
           employees.add(new Employee(3, "Paras", 100000L));
          employees.add(new Employee(2, "Deshraj", 80000L));

           System.out.println("Filter the employee have salary>=100000 ");

           /** using lambda to filter data. */
        Stream<Employee> filtered_emp = employees.stream().filter(p -> p.salary >= 100000); 
         
        // using lambda to iterate through collection 
        filtered_emp.forEach( 
                employee -> System.out.println(employee.name+": "+employee.salary
        ); 
     }
}

Output:
     Filter the employee have salary>=100000
     Algos: 130000
     Paras: 100000


Lambda for Event Listener example


package com.java8;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class LambdaEventListener {
     public static void main(String[] args) {
           JTextField tf = new JTextField();
           tf.setBounds(50, 50, 150, 20);
           JButton b = new JButton("click");
           b.setBounds(80, 100, 70, 30);

           /** lambda expression implementing here. */
           b.addActionListener(e -> {
                tf.setText("hello! Swing");
           });

           JFrame f = new JFrame();
           f.add(tf);
           f.add(b);
           f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           f.setLayout(null);
           f.setSize(300, 200);
           f.setVisible(true);
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...