Search This Blog

Friday 3 February 2017

Lambda expressions in Java 8

Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection.
A lambda expression can be understood as a concise representation of an anonymous function that can be passed around: it doesn’t have a name, but it has a list of parameters, a body, a return type, and also possibly a list of exceptions that can be thrown.
o    AnonymousAnonymous because it doesn’t have an explicit name like a method would normally have: less to write and think about!
o    FunctionFunction because a lambda isn’t associated with a particular class like a method is. But like a method, a lambda has a list of parameters, a body, a return type, and a possible list of exceptions that can be thrown.
o    Passed aroundA lambda expression can be passed as argument to a method or stored in a variable.
o    ConciseYou don’t need to write a lot of boilerplate like you do for anonymous classes.

Lambdas technically let you do anything that you could do prior to Java 8. But you no longer have to write clumsy code using anonymous classes.
 The result is that your code will be clearer and more flexible. For example, using a lambda expression you can create a custom Comparator object in a more concise way.

Before:
Comparator<Apple> byWeight = new Comparator<Apple>() {
public int compare(Apple a1, Apple a2){
return a1.getWeight().compareTo(a2.getWeight());
}
};


After (with lambda expressions):
Comparator<Apple> byWeight =
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());

Lambda Expression Syntax
Lambda expressions address the bulkiness of anonymous inner. A lambda expression is composed of three parts.
A lambda expression is composed of parameters, an arrow,
and a body.

Argument List
Arrow Token
Body
(int x, int y)
->
x + y
The body can be either a single expression or a statement block. In the expression form, the body is simply evaluated and returned. In the block form, the body is evaluated like a method body and a return statement returns control to the caller of the anonymous method. The break and continue keywords are illegal at the top level, but are permitted within loops. If the body produces a result, every control path must return something or throw an exception.
Take a look at these examples:
(int x, int y) -> x + y

() -> 42

(String s) -> { System.out.println(s); }
 
The first expression takes two integer arguments, named x and y, and uses the expression form to return x+y.
The second expression takes no arguments and uses the expression form to return an integer 42.
The third expression takes a string and uses the block form to print the string to the console, and returns nothing.
Lambda Examples
Runnable Lambda
public class RunnableTest {
  public static void main(String[] args) {
    System.out.println("=== RunnableTest ===");
       // Anonymous Runnable
    Runnable r1 = new Runnable(){
         @Override
      public void run(){
        System.out.println("Hello world one!");
      }
    };
   
    // Lambda Runnable
    Runnable r2 = () -> System.out.println("Hello world two!");
   
    // Run them
    r1.run();
    r2.run();
   
  }
}
Comparator Lambda
In Java, the Comparator class is used for sorting collections. In the following example, an ArrayList consisting of Person objects is sorted based on surName. The following are the fields included in the Person class.
public class Person {
private String givenName;
private String surName;
private int age;
private String eMail;
private String phone;
private String address;
}

The following code applies a Comparator by using an anonymous inner class and a couple lambda expressions.

public class ComparatorTest {
 public static void main(String[] args) {
  
    // Create List of Person
        List<Person> personList1 = null;
   
      // Sort with Inner Class
    Collections.sort(personList1, new Comparator<Person>(){
      public int compare(Person p1, Person p2){
        return p1.getSurName().compareTo(p2.getSurName());
      }
    });
   
    System.out.println("=== Sorted Asc SurName ===");
    for(Person p:personList1){
      System.out.println(
                  "Name: " + p.getGivenName() + " " + p.getSurName());
    }
   
    // Use Lambda instead
   
    // Print Asc
    System.out.println("=== Sorted Asc SurName ===");
    Collections.sort(personList1, (Person p1, Person p2) -> p1.getSurName().compareTo(p2.getSurName()));

    for(Person p:personList1){
System.out.println(
                  "Name: " + p.getGivenName() + " " + p.getSurName());
    }
   
    // Print Desc
    System.out.println("=== Sorted Desc SurName ===");
    Collections.sort(personList1, (p1p2) -> p2.getSurName().compareTo(p1.getSurName()));

    for(Person p:personList1){
System.out.println(
                  "Name: " + p.getGivenName() + " " + p.getSurName());
    }
   
  }
}

No comments:

Post a Comment