Trusted answers to developer questions

How to create a functional interface in Java

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

In this shot, we discuss how to create a functional interface in Java.

An interface that only consists of one abstract method is called a functional interface.

What is a lambda expression?

Lambda expressions can be used to denote the instance of a functional interface.

(String s, float f)  ->  {System.out.println(“Lambda Expression having ”+s+”and”+f);}

In the example above:

  • (String s, float f) is an argument list.
  • -> is the arrow token.
  • {System.out.println(“Lambda Expression having ”+s+”and”+f);} is the body of the lambda expression.

Solution

We can approach this problem by creating our own functional interface.

Then, in the main function of the class, we create an instance for the functional interface.

Now, we display something using the defined functional interface and lambda expression.

Code

Let’s take a look at the code.

interface funInterface
{
public int product(int a, int b);
}
class Main
{
public static void main(String[] args)
{
funInterface multiply = (a,b) -> a*b;
System.out.println("Multiplication result is: " +
multiply.product(190,30));
}
}

Explanation

  • In line 1, we create our own interface.
  • In line 3, we create an abstract method with two int type parameters.
  • In line 6, we create a Main class that has the main function inside it.
  • In line 10, we create an instance of our functional interface using a lambda expression.
  • In lines 11 and 12, we call the abstract method by using the previously created instance of the functional interface, and display the result with a message.

This is how we can create a functional interface using lambda expressions in Java.

RELATED TAGS

java
Did you find this helpful?