Sunday, September 27, 2015

Lambda Expressions in Java 8

Lambda Expressions:
  • Lambda expression is an anonymous function without any declarations. 
  • Lambda Expression are useful to write shorthand code and hence saves the effort of writing lengthy code. 
  • It promotes developer productivity, better readable and reliable code.
  • Lambda expressions can be converted to functional interfaces.
  • Lambda expressions can access effectively final variables from the enclosing scope..
Syntax of Lambda expression:
(arguments) -> {body}

Example of Lambda expression:
public class LambdaExpressions
{
  public static void main(String[] args)
  {        
    // Old way
    Runnable runnable = new Runnable() {
        public void run() {
            System.out.println("With out using Lambda Expressions .... ");
        }
    };
    
    Thread thread = new Thread(runnable);    
    thread.start();
    
    // Using Lambda Expressions
    Runnable runnable2 = () -> { System.out.println("With using Lambda Expressions .... ");};
    
    Thread thread2 = new Thread(runnable2);    
    thread2.start();    
  }
}
Output:
With out using Lambda Expressions .... 
With using Lambda Expressions .... 
Lambda expression arguments can contain zero or more arguments.
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Reddy");
names.add("Vasu");
names.add("Raja");
names.add("Viond");
names.add("Manoj");

new Thread(() -> { System.out.println("Empty arguments.");}) {      // empty arguments          
}.run();;
        
names.forEach(name -> System.out.println(name));            // one argument with out specifying data type 
names.forEach((name) -> System.out.println(name));          // one argument with out specifying data type
names.forEach((String name) -> System.out.println(name));   // one argument with specifying data type
Note: We can omit the datatype of the parameters in a lambda expression. And also we can omit the parentheses if there is only one parameter.

Lambda expression body can contain any number of statements or with out statement also.
If body contains more than one statement then curly braces is mandatory otherwise it is optional.
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Reddy");
names.add("Vasu");
names.add("Raja");
names.add("Viond");
names.add("Manoj");
        
names.forEach(((name) -> System.out.println(name))); // with out braces
        
names.forEach((name) -> {                            // with braces 
    System.out.println(name);
    System.out.println("Hello Mr. "+name);          
});

0 comments: