JAVA New Features – Lambda Expressions, Functional Interfaces

This Blog explains about Java 8 – New Features – Lambda Expressions, Functional Interfaces.

Lambda Expressions:

WHY:

Functional Programming

WHAT:

Anonymous Functions: Closures

Function – Method:

HOW:

Eg: 1

public void display()
{
System.out.println("Hi");
}

1) Remove Method Name

public void ()
{
System.out.println("Hi");
}

2) Remove return datatype

public ()
{
System.out.println("Hi");
}

3) Remove Access Modifiers if any.

()
{
System.out.println("Hi");
}

4) Add -> in between () and {}

() ->
{
System.out.println("Hi");
}

Eg. 2:

public void add(int no1, int no2)
{
System.out.println("Hi");
}

public void (int no1, int no2)
{
System.out.println("Hi");
}

public (int no1, int no2)
{
System.out.println("Hi");
}

(int no1, int no2)
{
System.out.println("Hi");
}

(int no1, int no2) ->
{
System.out.println("Hi");
}

(no1, no2) ->
{
System.out.println("Hi");
}

(no1) ->
{
System.out.println("Hi");
}

no1 -> { System.out.println("Hi"); }

Eg. 3:

public int add(int no1, int no2)
{
return no1 + no2;
}

(no1, no2) -> { return no1 + no2; }

Functional Interfaces:

Comparable / Runnable

An Interface with only one abstract method. Apart from this abstract method, we can have any number of default and static methods.

Without Lambda:

interface Contract
{
public void rule1();
}
class Citizen implements Contract
{
public void rule1()
{
System.out.println("Hi"); 
}
}
class Abcd
{
p s v main()
{
Contract ci = new Citizen();
ci.rule1(); 
}

@FunctionalInterface

Inner Classes:

Anonymous classes

Without Lambda:

public class Test3 {
public static void main(String[] args) {
    // TODO Auto-generated method stub

    Thread t = new Thread(
            new Runnable()
            {
                public void run()
                {
                    for(int i=1; i<=5; i++)
                        System.out.println("Child "+ i);
                }
            }
            );
    t.start();


}

With Lambda:

public class Test3 {
public static void main(String[] args) 
{
    Thread t = new Thread(
    () -> 
    {
        for(int i=1; i<=5; i++)
        {
            System.out.println("Child Thread "+ i);
        }
    }
                        );
    t.start();

}
}