Java Language Using lambda expression with your own functional interface


Lambdas are meant to provide inline implementation code for single method interfaces and the ability to pass them around as we have been doing with normal variables. We call them Functional Interface.

For example, writing a Runnable in anonymous class and starting a Thread looks like:

//Old way
new Thread(
        new Runnable(){
            public void run(){
                System.out.println("run logic...");

//lambdas, from Java 8
new Thread(
        ()-> System.out.println("run logic...")

Now, in line with above, lets say you have some custom interface:

interface TwoArgInterface {
    int operate(int a, int b);

How do you use lambda to give implementation of this interface in your code? Same as Runnable example shown above. See the driver program below:

public class CustomLambda {
    public static void main(String[] args) {

        TwoArgInterface plusOperation = (a, b) -> a + b;
        TwoArgInterface divideOperation = (a,b)->{
            if (b==0) throw new IllegalArgumentException("Divisor can not be 0");
            return a/b;

        System.out.println("Plus operation of 3 and 5 is: " + plusOperation.operate(3, 5));
        System.out.println("Divide operation 50 by 25 is: " + divideOperation.operate(50, 25));