Thursday 24 July 2014

Java 8 main Feature - Lambda Expressions or Basics of Lambda Expressions


Lambda Expression is newly added feature in Java 8, which is like a Javascript Closure or Scala, where function or reference of a function, together with a referencing environment a table storing a reference to each of the non-local variables of that function. So, we can say Lambda expression is similar to Closure or Scala, but not 100%.

like -
---------------------------------------------
var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

add();
add();
--------------------------------------------


So we can say Lambda Expressions, a new language feature, That enable you to treat functionality as a method argument, or code as data. Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly. 
Lambda expression is short form of writing method, and can be used in multiple ways. syntax is given below-

Lambda Expression syntax    


 (argument...) -> {statement}
Here method name, return type, and access modifier is not require to mention.

above is replica of below in old java

Accessmodifier ReturnType methodname(argument){
 //method statement
}


Lambda can be written in some more ways-
 
() -> 10           
 // no parameter and returns 10 
 
x -> x * x  
 // a number parameter parameter and returns the squared of number
 
(x, y) -> x – y  
   // two numbers parameter and returns their difference 
 
(int x, int y) -> x + y   
//two integers number and returns their sum 
 
(String s) -> System.out.print(s) 

 //string parameter and prints output to console


As you now aware of some basic syntax of Lambda expression so see some expmple below-

-------------------------------------------
String[] array= {"ABC", "BCD", "DEF", "GHI"};
List<String> list=  Arrays.asList(array);
 
new way coding style- 
  list.forEach((item)-> System.out.println(item));
 
old way coding style-
  for (String item: list) {
    System.out.println(item);
  }
------------------------------------------
Method reference is also java 8 feature which you can plug with Lambda expression and get some more shorter way of code. It denote by :: (two colon) operator.
method references; shortcuts that you can use anywhere you would use a lambda. There are four types of method referenc-
  1. Reference to a static method-         ContainingClass::staticMethodName 
  2. Reference to an instance method of a particular object - ContainingObject::instanceMethodName 
  3. Reference to an instance method of an arbitrary object of a particular type - ContainingType::methodName
  4. Reference to a constructor-         ClassName::new
   Example and plug with Lambda by below Comparison-

  As Method Reference                                   As Lambda Expression
  String::valueOf                  (str) -> String.valueOf(str)
  x::toString                      () -> "test".toString()
 String::toString                 (s) -> s.toString()
 String::new                      () -> new String()

---------------------------------------------------------------
//Iterate item by Method reference (::) two colon operator
//by using reference to a static method
  list.forEach(System.out::println);
 
//instance method of object call 
 String x = "test";
 function(x::toString);
------------------------------------------------
 
Anonymous classes also can be replaced with lambda expressions. 
The same thing happens when implementing the Runnable interface
-----------------------------------------------------------
// older style thread example 
new Thread(new Runnable() {
 @Override
 public void run() {
  System.out.println("Thread example");
 }
}).start();
 
// Using lambda expression thread
new Thread(() -> System.out.println("Thread example")).start(); 
---------------------------------------------------------------- 
 
Lambda with Stream
Java 8 added some Stream APIs. java.util.stream.Stream interface.
So, these Collection Stream method can be used by Lambda. like- map, 
filter,limit, max, min, sort and so on.
----------------------------------------
//Old way of coding
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
for(Integer n : list) {
    int x = n * n;  //calculate the square of number
    System.out.println(x);
}
//New way of coding
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
list.stream().map((x) -> x*x).forEach(System.out::println);
Here we are getting the stream() and mapping all the stream element to 
x -> x*x then we are using method reference to print all the squared value.
-------------------------------------------------- 
 
That's it about Lambda!!!!

No comments:

Post a Comment