Friday, 6 January 2017

Lambda in Java 1.8

This post is not a detailed treatise on Lambda expressions, but rather shows an example of how a program can be implemented differently. On page 444 of Java, The Complete Reference, Ninth Edition by Herbert Schildt, a short program has been written that uses a predefined functional interface called Function to calculate factorial of a number.

Below program calculates the factorial of a number, but uses the UnaryOperator interface instead. UnaryOperator represents an operation on a single operand (an integer in our case) that produces a result of the same type as its operand (factorial of the operand integer). The reason for the choice of UnaryOperator is not difficult to see in that we have an output for a single input. Following is the code:

package com.lambda;

// This program uses the UnaryOperator built-in functional interface

import java.util.function.UnaryOperator;

class UnaryOperatorInterface {
public static void main(String args[])
{
// This block lambda computes the factorial of an integer
// UnaryOperator is the functional interface.
UnaryOperator<Integer> factorial = (n) -> {
    int output = 1;
    for(int i=1; i <= n; i++)
        output = i * output;
    return output;
};
System.out.println("The factorial of 6 is " + factorial.apply(6));
}
}


The program output is shown below:

The factorial of 6 is 720