Lamda Expression in java-8

Java 8 introduced a feature like functional programming lamda expression.Although itz not purely fuctional programming itz almost like as functional programming. We can easily write some code using this lamda expression.Such like in java swing litsener event we can use this lamda expression. In our traditional java programming we add a buttonActionListener like this
btn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Traditional programming!");
    }
});
But if we use lamda expression we can minize code in one line code like this.
 
btn.addActionListener((e) -> System.out.println("With lambda expressions !"));
As we see here lamda expression has two part 1. Left of the arrow sign(->) which indicate how much parameter will accepted by the method 2. Right of the arrow sign(->) which indicate the body
Syntex of lamda expression like this (agrument) -> (body).
Compiler will automatically recognise lamda expression in the unimplemented consumer interface witch is called functional interface declared by @FunctionalInterface annotation. Rules to write a lamda Expression 1. Can have zero parameters. like this
    //********************Runable class***************************/
        //*Without lamda expression*/
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("With Runnable -1");
            }
        };

        //*With Lamda Expression*/
        Runnable r2 = () -> System.out.println("With Runnable -2");
2. Parameters separated by commas(p1,p2) like this *************************************************************
Collections.sort(products, (Product p1, Product p2) -> p2.getName().compareTo(p1.getName()));
************************************************************* here products is a List of Product. and Product represent a POJO class. 3. The body of the lambda expressions can contain zero, one or more statements. *************************************
//zero statement
 () -> "Just a string as return type"
//one statement
 sum(numbers, n -> n<4 -="" more="" n="" numbers="" one="" statements="" sum="" than=""> n<4 a="" and="" here="" int="" integer="" is="" ist="" list="" method="" n="" nteger="" numbers="" of="" public="" represent="" static="" sum="" values=""> numbers, Predicate p) {
        int total = 0;
        for (int number : numbers) {
            if (p.test(number)) {
                total += number;
            }
        }
        return total;
    }
 
*********************************** Here Predicate is an funtional interface Now the time to work with example...:P *******************************Main Class******************
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;
import java.util.function.Predicate;

/**
 * Created by Flop Coder on 7/6/14.
 */
public class Main {

    public static void main(String[] args) {
        //********************Runable class***************************/
        //*Without lamda expression*/
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("With Runnable -1");
            }
        };

        //*With Lamda Expression*/
        Runnable r2 = () -> System.out.println("With Runnable -2");

        r1.run();
        r2.run();

        //*********************Comparator Lamda**************************/

        //*Sorting products without lamda*/
        List products = Product.creatShortList();
        Collections.sort(products, new Comparator() {
            @Override
            public int compare(Product o1, Product o2) {
                return o1.getSerialNumber().compareTo(o2.getSerialNumber());
            }
        });

        System.out.println("Sorted Products");

        //*Normally*/
        for (Product product : products) {
            System.out.println(product.getSerialNumber());
        }
        //* In lamda expression*/
        products.forEach((Product product) -> System.out.println(product.getSerialNumber()));

        //*Sorted desc order according to name and with lamda expression*/
        Collections.sort(products, (Product p1, Product p2) -> p2.getName().compareTo(p1.getName()));

        System.out.println("Sorted Products");
        products.forEach((Product product) -> System.out.println(product.getName()));

        List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
        //*Eta expression in functional programming*/
        numbers.forEach(System.out::println);

        System.out.println("Sum of Numbers :: " + sum(numbers, n -> n < 4 && n % 2 == 0));

        //With custom functional interfaces
        printRole(()-> System.out.println("Here is Role"));

    }

    public static void printRole(Role role)
    {
        role.printRole();
    }
    public static int sum(List numbers, Predicate p) {
        int total = 0;
        for (int number : numbers) {
            if (p.test(number)) {
                total += number;
            }
        }
        return total;
    }
}
*********************Product class*********************************
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Flop Coder on 7/6/14.
 */
public class Product {

    private String serialNumber;
    private String name;
    private String unitPrice;
    private String about;

    public String getSerialNumber() {
        return serialNumber;
    }

    public void setSerialNumber(String serialNumber) {
        this.serialNumber = serialNumber;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUnitPrice() {
        return unitPrice;
    }

    public void setUnitPrice(String unitPrice) {
        this.unitPrice = unitPrice;
    }

    public String getAbout() {
        return about;
    }

    public void setAbout(String about) {
        this.about = about;
    }


    public static List creatShortList() {
        List products = new ArrayList();
        for (int i = 9; i >= 1; i--) {
            Product product = new Product();
            product.setName("Samsung_"+i);
            product.setSerialNumber("Serial_"+i);
            product.setUnitPrice("price_"+i);
            product.setAbout("about_"+i);
            products.add(product);
        }
        return products;
    }
}
****************************Role class*********************************
/**
 * Created by Flop Coder on 7/6/14.
 */
@FunctionalInterface
public interface Role {
    public void printRole();
}
********************************************* NB: I am new with java8. I have study some blogs and docs and write a simple code for this.
I think it will help some people with new in java8.
You can download source code from this link WithJava8
 Thanks. Happy Coding...:P
Reactions

Post a Comment

0 Comments