Java 8 – Lambda Expressions Primer

Java is object oriented programing language i.e. everything in java revolves around the object. In Java all the functions and variables are the part of Classes and we have to use object of that class to invoke the same. some other languages like  C, JavaScript are functional programming languages. Java is currently one of the most popular programming languages being used. It has about 10 million users.  Java 8 is the latest release for Java that contains new features, enhancements and bug fixes to improve efficiency to develop and run Java programs.
Java 8 comes up with some new features.Some of them are:-

agami Lambda Expression
agami Method References
agami Default Method
agami Stream API
agami Date And Time API
agami Nashron i.e JavaScript Base Engine & more.

 In this blog I will explain the functional interface, consumer and supplier Interfaces and Lambda Expressions.

What is Functional Interface?

Functional Interface : Functional interface is the interface with one method.Functional Interfaces contains only one method which can be default or static method.Several Existing interfaces are Runnable, Action Listener and callable.
For Using functional Interface We use @FunctionalInterface annotation in java.The Interfaces are useful when you want to access an element and perform an operation on it.Functional Interfaces are provided in java.function.util package.The methods of functional interfaces can be implemented by using lambda expression.The Complier will return the meaningful error when you define the interface with @FunctionalInterface.

What are Consumer and Supplier Interfaces?
Consumer Interface : The Consumer Interface<T> defines an abstract method  accept that takes an object of generic type and return no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects. Consumer as the name suggests  consumes something .

Consumer Interface has 2 methods :
1. void accept : contains a code that is executed on (<T> t).
2. default Consumer<T> and Then(Consumer<? super T> after) : This   method returns a consumer that is executed after the previous one and enables you to execute a chain of consumers.

Examples:

(i) @FunctionalInterface
public interface Consumer<T> {
   void accept(T t);
}
(ii)  Java 8 provides a forEach method to do the same thing...
intList.forEach(new Consumer<Integer>() {
   public void accept(Integer i) {
      System.out.println(i);
   }
}
(iii) List<Integer>  list = Arrrays.asList(1,2,3);
Consumer<Integer> consumer = x -> System.out.println(x);
list.forEach(consumer);

Supplier Interface   :    A Supplier object receives no arguments. We use an empty argument list to specify a lambda expression with no arguments. A Supplier provides values and we call get() on it to retrieve its value—it may return different values when called more than once
Example :

import java.util.function.*;
public class Supplier {
    static void display(Supplier<Integer> arg) {
	System.out.println(arg.get());
    }
    public static void main(String[] args) {
	display(() -> 100);
	display(() -> (int) (Math.random() * 100));
    }
}
Output :
10
23
About Lambda Expression

What is Lambda Expression ?
Lambda expression is a powerful feature of java 8. It is the replacement of anonymous inner class which is very compact.It is anonymous function  to reduce  extra overhead of Anonymous class. Lambda expressions are also known as closure or anonymous function in Java. They are actually commonly used to avoid coding unnecessary methods. Thus, if the
functionality is only needed once or for a short amount of
time, lambda expressions help make code clearer and concise
Structure of Lambda Expression
Lambda Expression can be divided into three parts .
1. Arrow (->)
2.Parameter  or arguments List
3.Body
Syntax :    parameter -> body
Arrow : A arrow separates the parameter and the body.
Arguments List :
No arguments  : Lambda Expression contaion zero or more arguments.
ex: () -> {System.out.println(“Agami Technology Pvt Ltd”);}
one Argument : Lambda Expression with one argument.
(int a ) – {    (” System .out.println(“Agami Technologies pvt ltd”+ a);}
Body :
body of lambda Expression can be a single statement or a block of statements.
Performance of Lambda Expression : – Performance of Lambda Expression differs from one  programing language to another.In Some Language the use the lambda expression not only gives the look of code clear and more concise .but also gives the faster execution time.
Where to use Lambda ?
If you want to implement functional interfaces than use Lambda expressions.
Sorting Example :

import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
public class SortingExample {
   public static void main(String args[]){
      List<String> names1 = new ArrayList<String>();
      names1.add("Madhav ");
      names1.add("Raghav ");
      names1.add("Krishan ");
      List<String> names2 = new ArrayList<String>();
      names2.add("Raghav ");
      names2.add("krishan ");
      names2.add("Madhav ");
     SortingExample sorting = new SortingExample();
      System.out.println("List with java7");
      sorting.sortUsing7(names1);
      System.out.println(names1);
      System.out.println("List with java8");
      sorting.sortUsing8(names2);
      System.out.println(names2);
   }

before lambda Expression :

private void sortUsing7(List<String> names){
      Collections.sort(names, new Comparator<String>() {
         @Override
         public int compare(String s1, String s2) {
            return s1.compareTo(s2);
         }
      });
   }

After Lambda Expression :

private void sortUsing8(List<String> names){
      Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
   }
}

Iterating  Over List Using Lambda Expression :
List list = Arrays.asList(“Java”, “.Net”, “Android”, “Go”,”Php”);
features.forEach(n -> System.out.println(n));

         With the use of Lambda expressions we can reduce many lines of code and make the code easier to read .The addition of lambda expressions to Java 8 provides for more functional, concise, and readable coding. In addition,given enough execution time, the new lambda expressions can provide a performance advantage.

References :
http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html
https://github.com/winterbe/java8-tutorial#lambda-expressions