Monday, November 3, 2014

Java Lambda Expression

Lambdas (also known as closures) are the biggest and most awaited language change in the whole Java 8 release. A lambda expression is an anonymous function. Simply put, it's a method without a declaration, i.e., access modifier, return value declaration, and name. 

To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. You can assign this expression to a delegate type

Benefits:
    1. Reduced typing. 
    2. No need to specify the name of the function,
    3. No need to specify return type, and its access modifier. 
    4. When reading the code you don't need to look elsewhere for the method's definition. 

Full Working Code:
    ArrayList<Student> list = new ArrayList<Student>();
    Student s = new Student("AAA");
    Student s1 = new Student("BBB");
    Student s2 = new Student("CCC");
    list.add(s);
    list.add(s1);
    list.add(s2);

   //Lambda expression   
    list.forEach( e -> {
      Student res= (Student)e;
      System.out.println( res.name ) ;
    });
   
  }
}

class Student{
  public String name; 
  public Student(String name){
    this.name= name;
  } 
  
}