Friday, October 14, 2016

Java 8 lambda expression & method reference made easy

Lambda expression facilitates functional programming in Java. 

  • Lambda expression is a function which can be created without belonging to any class. Lambda expression can be passed around as if it was an object and executed on demand as method reference.
  • Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. Following demonstrates serious ways of using lamda expression.

Method reference:

A method reference is the shorter more concise syntax for a lambda expression that executes just ONE method.

There are four types of method references:
  • A method reference to a static method.
  • A method reference to an instance method of an object of a particular type.
  • A method reference to an instance method of an existing object.
  • A method reference to a constructor.

Sample program:

// Functional interfaces are heart of lambda expression
interface FuncIface {
    public void referenceDemo(); //Only one abstract method is allowed in functional interface

//Example class
class LambdaExample {
    private static int i;
    public static void commonMethod() {
        System.out.println("This method is already defined." + ++i);//can i use static method as lambda method reference?
    public LambdaExample() {
        System.out.println("LambdaExample constructor called");

    public static void main(String[] args) {

        // Anonymous class
        FuncIface demoOne = new FuncIface() {
            public void referenceDemo() {
                System.out.println("LambdaExample -> " + this);//What will this print?

        // Lambda implementation
        FuncIface demo = () -> LambdaExample.commonMethod();

        // Static method can be used as method reference
        FuncIface demoTwo = LambdaExample::commonMethod;
        // Instance method reference
        LambdaExample o = new LambdaExample();
        FuncIface demoThree = o::m1;
        // Method reference.
        FuncIface demoFour = () -> {
        // Constructor can be used as method reference using ::new
        FuncIface demo4 = LambdaExample::new; //LambdaExample constructor used as method reference
        FuncIface demo5 = String::new;//String constructor used as method reference
    public void m1() {
        System.out.println("m1() called");



This method is already defined.1
LambdaExample -> LambdaExample$1@15db9742
This method is already defined.2
This method is already defined.3
LambdaExample constructor called
m1() called
This method is already defined.4


No comments:

Post a Comment

Example code to connect node.js REST service with Eureka discovery service

Eureka is Spring based discovery service developed by Netflix. To know how Eureka is used at Netflix visit: