Functional interfaces code example

Introduction

This post will demonstrate the usage of functional interfaces with a code example.Its really important to have a clear understanding of functional interfaces to learn lambda expressions.

In a nutshell, a functional interface is an interface that has only one abstract method.

Code examples

Example 1:

Compute is annotated with @FunctionalInterface indicating that its a functional interface.It has a single abstract method which takes 2 integers as parameters and returns an integer.

package com.ppkcodes.examples;

@FunctionalInterface
public interface Compute {
    public abstract int performCompute(int x,int y);
}

ComputeImpl is the implementation class for Compute interface.As you can see, I have added 3 implementations .

  • add : Takes 2 integers as parameters , adds them and returns the result.
  • subtract: Takes 2 integers as parameters, subtracts them and returns the result.
  • multiply:Takes 2 integers as parameters , multiplies them and returns the result.
package com.ppkcodes.examples;

public class ComputeImpl {
    public static void main(String[] args) {
        Compute add = (x, y) -> {
            return x + y;
        };

        Compute subtract = (x, y) -> {
            return x - y;
        };

        Compute multiply = (x, y) -> {
            return x * y;
        };

        System.out.println("Adding 2 numbers :"+ add.performCompute(1,5));
        System.out.println("subtracting 2 numbers :"+ subtract.performCompute(100,5));
        System.out.println("Multiplying 2 numbers :"+ multiply.performCompute(2,5));

    }
}
Result:
Adding 2 numbers :6
subtracting 2 numbers :95
Multiplying 2 numbers :10

Example 2:

Runnable interface also qualifies as a functional interface since it contains a single abstract method run().In multi threaded applications , we will be required to implement Runnable interface.lets use a Lambda expression of Java8 to implement the same.

Check the lines Lines 6 to 9 for the implementation of Runnable using lambda.

package com.codingbrains.examples;

public class RunnableExample {

  public static void main(String[] args) {
    Runnable runnable = () -> {
      for(int i=0;i<5;i++)
      System.out.println("Runnable with Lambda");
    };
    new Thread(runnable).start();
  }
}
Output:
Runnable with Lambda
Runnable with Lambda
Runnable with Lambda
Runnable with Lambda
Runnable with Lambda

You may also like...

1 Response

  1. May 8, 2020

    […] this post for more code examples of functional interfaces. Few more functional interface examples specific to java8 can be found […]

Leave a Reply

Your email address will not be published.